0

我用 Python 和 Beautiful Soup 构建了一个网络爬虫

有时某些元素存在,有时则不存在。我有很多。为每个“find”和/或“find_all”设置自定义异常对我来说真的没有意义

我只想忽略这些错误,以便我的刮刀不会因异常而停止。这是我的终端的错误输出:

Traceback (most recent call last):
  File "listing-scraper.py", line 80, in <module>
    'engine_size':soup.find("span",{"id":"infoEngine Size"}).contents[0],
AttributeError: 'NoneType' object has no attribute 'contents'

我怎么能继续?

这是我的源代码的一个片段 - 所以你可以看到它是如何设置的。(请客气,我是 Python 新手)

    dealer_info = {
        'name':dealer_box.find("h4").contents[0],
        'address':dealer_address,
        'phone':re.sub(r'[^\d.]+','',soup.find("div",{"class":"PhoneNumber"}).contents[0]),
        'logo':soup.find("div",{"class":"dealerLogo"}).img['src'],
        'about':dealer_about,
        'website':website,
        'video':dealer_video
    }

    thumbnails = soup.find("div",{"class":"imageThumbs"}).find_all('img')
    dealer_thumbnails = []

    for thumbnail in thumbnails:
        dealer_thumbnails.append(thumbnail['src'])

    motorcycle = {
        'insert_date':time.time() * 1000,
        'year':soup.find("span",{"id":"infoYear"}).contents[0],
        'make':soup.find("span",{"id":"infoMake"}).contents[0],
        'model':soup.find("span",{"id":"infoModel"}).contents[0],
        'type':soup.find("span",{"id":"infoType"}).contents[0],
        'location':soup.find("span",{"id":"infoLocation"}).contents[0],
        'color':soup.find("span",{"id":"infoColor"}).contents[0],
        'engine_size':soup.find("span",{"id":"infoEngine Size"}).contents[0],
        'description':description,
        'price':soup.find("h3",{"class":"askingPriceNumber"}).contents[1],
        'thumbnails':dealer_thumbnails,
        'dealer_info':dealer_info
    }

    listing.update(motorcycle)
4

1 回答 1

2

考虑类似的事情:

def getcontents(item, index):
    if item is None:
        return None
    return item.contents[index]

motorcycle = {
        'insert_date':time.time() * 1000,
        'year':getcontents(soup.find("span",{"id":"infoYear"}), 0),
        ...

通常,如果您可以避免首先引起异常,则不应忽略该异常。

于 2012-05-31T17:24:19.117 回答