python - 使用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")
谢谢!
解决方案
由于您是初学者,我会以这种方式详细说明您的代码。只需使用这样的 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 ""
这将得到你所需要的。
推荐阅读
- java - 如何实例化具有带参数的私有构造函数的泛型类
- python - pydotplus 工作不正常,决策树可视化错误?
- android - (实例中缺少 Vulkan 1.0 API)通过 Android Studio 3.5 和 3.6 Canary 9 启动 Android Emulator(Q API 29)时
- apache-kafka - Spring Cloud @StreamListener 消费者未在消费者组中注册 CONSUMER-ID、HOST 和 CLIENT-ID
- c# - lambda中的初始化惰性字段未在多个线程之间重用
- amazon-web-services - 使用参数在 AWS SAM 中动态创建资源名称
- react-native - 为什么我的模态高度占据了屏幕的一半?
- hibernate - 使用它们的 Id 从两个表创建一个表
- python-3.x - Python list() 与 append()
- matlab - 我的卷积码在完全重叠后停止工作。有什么建议么?