【发布时间】:2020-05-18 15:17:35
【问题描述】:
我目前正在从事一个涉及网页抓取房地产网站的项目(用于教育目的)。我正在从房屋列表中获取数据,例如地址、价格、卧室等。
在构建和测试打印功能(它成功!)之后,我现在正在为列表中的每个数据点构建一个字典。我将该字典存储在一个列表中,以便最终使用 Pandas 创建一个表并发送到 CSV。
这是我的问题。我的列表显示一个没有错误的空字典。请注意,我已经成功抓取了数据,并且在使用打印功能时看到了数据。现在,在将每个数据点添加到字典并将其放入列表后,它什么也不显示。这是我的代码:
import requests
from bs4 import BeautifulSoup
r=requests.get("https://www.century21.com/real-estate/colorado-springs-co/LCCOCOLORADOSPRINGS/")
c=r.content
soup=BeautifulSoup(c,"html.parser")
all=soup.find_all("div", {"class":"infinite-item"})
all[0].find("a",{"class":"listing-price"}).text.replace("\n","").replace(" ","")
l=[]
for item in all:
d={}
try:
d["Price"]=item.find("a",{"class":"listing-price"}.text.replace("\n","").replace(" ",""))
d["Address"]=item.find("div",{"class":"property-address"}).text.replace("\n","").replace(" ","")
d["City"]=item.find_all("div",{"class":"property-city"})[0].text.replace("\n","").replace(" ","")
try:
d["Beds"]=item.find("div",{"class":"property-beds"}).find("strong").text
except:
d["Beds"]=None
try:
d["Baths"]=item.find("div",{"class":"property-baths"}).find("strong").text
except:
d["Baths"]=None
try:
d["Area"]=item.find("div",{"class":"property-sqft"}).find("strong").text
except:
d["Area"]=None
except:
pass
l.append(d)
当我调用l(包含我的字典的列表)时 - 这就是我得到的:
[{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{},
{}]
我正在使用 Python 3.8.2 和 Beautiful Soup 4。任何想法或帮助将不胜感激。谢谢!
【问题讨论】:
-
考虑删除您的Pokemon exceptions,它会不加选择地抑制错误并让人难以分辨出什么是失败的。
-
您的代码每次都进入 except 块,因此在第一次尝试时看起来像是出错了。你在这里有很多尝试,有更好的方法来处理这个
-
如果你取出所有的 try 块,你会得到错误
AttributeError: 'dict' object has no attribute 'text' -
存在例外,因为我会收到大量 attributeError: 'NoneType' 错误。一些房地产列表缺少数据点并且不包含卧室数量的数据,因此我添加了例外以处理该问题并在没有相关信息时显示 None。
-
那么除了特定的错误:
except AttributeError:。否则,您将抑制任何和所有错误,包括您没有预料到的错误,这些错误会告诉您如何解决问题。或者写一个条件if foo is None:。
标签: python python-3.x list dictionary beautifulsoup