加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用Beautiful Soup查找特定的类

发布时间:2020-12-20 12:11:48 所属栏目:Python 来源:网络整理
导读:我正在尝试使用Beautiful Soup从Zillow那里获取住房价格数据. 我按属性ID获取网页,例如. http://www.zillow.com/homes/for_sale/18429834_zpid/ 当我尝试find_all()函数时,我没有得到任何结果: results = soup.find_all('div',attrs={"class":"home-summary
我正在尝试使用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> s与类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,144 </span></div></body></html>'
soup = BeautifulSoup(html,"html5lib")

results = soup.find_all('div',attrs={"class":"home-summary-row"})
print(results)

解决方法

根据 W3.org Validator,HTML存在许多问题,例如杂散结束标记和跨多行分割的标记.例如:

<a 
href="http://www.zillow.com/danville-ca-94526/sold/"  title="Recent home sales" class=""  data-za-action="Recent Home Sales"  >

这种标记可以使BeautifulSoup解析HTML变得更加困难.

您可能想尝试运行某些东西来清理HTML,例如从每行末尾删除换行符和尾随空格. BeautifulSoup还可以为您清理HTML树:

from BeautifulSoup import BeautifulSoup
tree = BeautifulSoup(bad_html)
good_html = tree.prettify()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读