热线电话:13121318867

登录
2019-02-21 阅读量: 678
如何用python值进行webscraping时防止错误

现在我正在尝试通过房地产网站搜索属性数据。我有一个代码,通过属性列表获取数据,然后转到每个属性的页面,并获取更详细的数据。它的工作原理但问题是,如果缺少任何字段,我会收到导致异常的错误并使其跳转到下一个属性。相反,我想让它为任何我不熟悉Python和webscraping的数据留下空值,这样可能会有更多关于如何清理我的代码的见解,所以请随意评论,但主要是我我只是试图让它在找到缺失数据的地方放置空值。这是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")

0.0000
5
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子