首页 > 解决方案 > 使用python进行网络抓取并且值不存在时如何防止错误?

问题描述

现在我正在尝试浏览一个房地产网站并抓取有关房产的数据。我有一个通过属性列表获取数据的代码,然后转到每个属性的页面并获取更详细的数据。它可以工作,但问题是如果缺少任何字段,我会收到一个导致异常并使其跳到下一个属性的错误。相反,我想让它为任何丢失的数据设置一个空值,我是 Python 和网络抓取的新手,所以可能会有更多关于如何清理我的代码的见解,所以也可以随意评论,但主要是我我只是想让它把空值放在它发现丢失数据的地方。这是prop_list是html代码的代码

for item in prop_list:
    try:
        d ={}
        d["address"] = item.find("span", {"itemprop":"streetAddress"}).text
        d["city"] = item.find("span", {"itemprop":"addressLocality"}).text
        d["state"] = item.find("span", {"itemprop":"addressRegion"}).text
        d["zip_code"] = item.find("span", {"itemprop":"postalCode"}).text
        d["price"] = item.find("span", {"class":"data-price"}).text
        d["lot_sqft"] = item.find("li", {"data-label":"property-meta-lotsize"}).find("span", {"class":"data-value"}).text           
        link = item.find("a").get("href")
        url = "https://www.realtor.com" + link
        d["url"] = url
        d["longitude"] = item.find("meta",{"itemprop":"longitude"}).get("content")
        d["latitude"] = item.find("meta",{"itemprop":"latitude"}).get("content")
        desc_link = requests.get(url,headers=headers)
        b = desc_link.content
        temp = BeautifulSoup(b,"html.parser")
        d["description"] = temp.find("p", {"class": "word-wrap-break"})
        d["year_built"] = temp.find("li", {"data-label": "property-year"}).find("div", {"class":"key-fact-data ellipsis"}).text

        l.append(d)

    except:
        print("exception occurred")

谢谢!

标签: pythonweb-scrapingbeautifulsoup

解决方案


由于您是初学者,我会以这种方式详细说明您的代码。只需使用这样的 if-else 语句:

if item.find("span", {"itemprop" : "streetAddress"}):
    d["address"] = item.find("span", {"itemprop":"streetAddress"}).text
else:
    d["address"] = "" # or None

现在对每个元素都这样做会很忙,所以以 Pythonic 的方式:

d["address"] = item.find("span", {"itemprop":"streetAddress"}).text if item.find("span", {"itemprop":"streetAddress"}) else ""

这将得到你所需要的。


推荐阅读