我的代码和beautifulsoup中出错了

问题描述 投票:0回答:3
import requests
from bs4 import BeautifulSoup
from mysql import connector

first_url = "https://www.freelancer.com/jobs/?keyword=python"

response = requests.get(first_url)

page = BeautifulSoup(response.text, 'html.parser')
items = page.find_all("div", attrs={"class": "JobSearchCard-item-inner"})
for index, item in enumerate(items):
    title = item.find("a", attrs={"class": "JobSearchCard-primary-heading-link"}).text.strip()
    timeLeft = item.find("span", attrs={"class": "JobSearchCard-primary-heading-days"}).text.strip()

    try:
        verified = 'VERIFIED' == item.find("div", attrs={"class":"JobSearchCard-primary-heading-status Tooltip--top"}).text.strip()
    except:
        verified = False

    description = item.find("p", attrs={"class": "JobSearchCard-primary-description"}).text.strip()
    # do tags section
    price = item.find("div", attrs={"class": "JobSearchCard-secondary-price"}).text.strip().split()
    price = ' '.join(price)
    bids = int(item.find("div", attrs={"class": "JobSearchCard-secondary-entry"}).text.strip().split()[0])
    print("title: ", title)
    print("time left: ", timeLeft)
    print("verified: ", verified)
    print("description: ", description)
    print("price: ", price)
    print("bids: ", bids)
    print("\nindex: {} ------------------------------------------------------------------\n".format(index))

嗨,当我运行我的代码时出现此错误,我不知道为什么我得到这个,PRICE变量不应该是NoneType。

Traceback (most recent call last):
  File "c:\Users\jackson\Desktop\GPFW.py", line 22, in <module>
    price = item.find("div", attrs={"class": "JobSearchCard-secondary-price"}).text.strip().split()
AttributeError: 'NoneType' object has no attribute 'text'

如果您注意到代码,程序应打印出TITLE,TIEMLEFT,DESCRIPTION,VERIFIED变量,然后打印出错误。问题是什么?

python beautifulsoup
3个回答
2
投票

由于这篇文章你得到这个错误

enter image description here

它没有价格或出价。您只需添加一个try-except块,并在此帖子中设置出价和价格所需的值。

try:
    price = item.find("div", attrs={"class": "JobSearchCard-secondary-price"}).text.strip().split()
except AttributeError:
    price=''
price = ' '.join(price)
try:
    bids = int(item.find("div", attrs={"class": "JobSearchCard-secondary-entry"}).text.strip().split()[0])
except AttributeError:
    bids='' 

1
投票

如果您从源网页滚动浏览结果列表,则会有一行没有发布价格(也没有出价)。因此,在撰写本文时,错误是合法的,因为您要查找的元素对于该条目不存在。

要解决您的问题,请简单地添加检查元素是否存在。如果是,则提取文本

price = item.find("div", attrs={"class": "JobSearchCard-secondary-price"})
if price:
    price = price.text.strip().split()
else:
    price = "No Avg Price"

0
投票

nonetype错误是由“item.find(”div“,attrs = {”class“:”JobSearchCard-secondary-price“})”不是可用的数据类型引起的,例如字符串而不是int或自定义类型,例如a名称类型,因此您可能希望查看运行该行时收到的数据,并在尝试格式化之前将其转换为可用的数据类型。

© www.soinside.com 2019 - 2024. All rights reserved.