我正在尝试使用 Beautiful Soup 从 Zillow 抓取房价数据。
我通过属性 ID 获取网页,例如。 http://www.zillow.com/homes/for_sale/18429834_zpid/
当我尝试 find_all()
函数时,我没有得到任何结果:
results = soup.find_all('div', attrs={"class":"home-summary-row"})
但是,如果我使用 HTML 并将其削减到我想要的部分,例如:
<html>
<body>
<div class=" status-icon-row for-sale-row home-summary-row">
</div>
<div class=" home-summary-row">
<span class=""> $1,342,144 </span>
</div>
</body>
</html>
我得到 2 个结果,都 <div>
类 home-summary-row
。所以,我的问题是,为什么在搜索整页时没有得到任何结果?
工作示例:
from bs4 import BeautifulSoup
import requests
zpid = "18429834"
url = "http://www.zillow.com/homes/" + zpid + "_zpid/"
response = requests.get(url)
html = response.content
#html = '<html><body><div class=" status-icon-row for-sale-row home-summary-row"></div><div class=" home-summary-row"><span class=""> $1,342,144 </span></div></body></html>'
soup = BeautifulSoup(html, "html5lib")
results = soup.find_all('div', attrs={"class":"home-summary-row"})
print(results)
原文由 SFBA26 发布,翻译遵循 CC BY-SA 4.0 许可协议
根据 W3.org Validator 的说法,HTML 存在许多问题,例如杂散的结束标记和跨多行拆分的标记。例如:
这种标记会使 BeautifulSoup 更难解析 HTML。
您可能想尝试运行一些程序来清理 HTML,例如删除每行末尾的换行符和尾随空格。 BeautifulSoup 还可以为您清理 HTML 树: