【问题标题】:AttributeError: 'NoneType' object has no attribute 'text' - BeautifulsoupAttributeError:“NoneType”对象没有属性“文本”-Beautifulsoup
【发布时间】:2020-11-22 00:04:38
【问题描述】:

在beautifulsoup 中提取文本时遇到问题:

data=requests.get("https://www.habitaclia.com/pisos-barcelona.htm?gclid=Cj0KCQiAkuP9BRCkARIsAKGLE8UM9G9s2MhPVtfXl2wo81qT62dqCwkVeV1zVSlPz_G1Nt0QcSoyKTYaAv55EALw_wcB")

soup=BeautifulSoup(data.text, "html5lib")

anuncis = soup.find_all("div", {"class":"list-item-info"})

data=[]
for anunci in anuncis:
    preu = [anunci.find("span", attrs={"itemprop":"price"}).text]
    data.append(preu) 
print(data)

我尝试了不同的解析器 html、html5、xlml,但似乎都不起作用。

知道为什么我不能提取文本吗?

提前致谢。

干杯

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    似乎有些div.list-item-info 没有span,里面有itemprop=price。所以,你需要像这样检查它们

    import requests
    from bs4 import BeautifulSoup
    
    data=requests.get("https://www.habitaclia.com/pisos-barcelona.htm?gclid=Cj0KCQiAkuP9BRCkARIsAKGLE8UM9G9s2MhPVtfXl2wo81qT62dqCwkVeV1zVSlPz_G1Nt0QcSoyKTYaAv55EALw_wcB")
    
    soup=BeautifulSoup(data.text, "lxml")
    
    anuncis = soup.find_all("div", {"class":"list-item-info"})
    
    data=[]
    for anunci in anuncis:
        preu = anunci.find("span", attrs={"itemprop":"price"})
        if preu:
            data.append([preu.text])
    print(data)
    

    结果

    [['190.000 €'], ['156.371 €'], ['256.489 €'], ['218.000 €'], ['225.000 €'], ['480.000 €'], ['1.325.000 €'], ['439.000 €'], ['1.495.000 €'], ['339.000 €'], ['780.000 €'], ['549.000 €'], ['549.000 €'], ['535.000 €'], ['460.000 €']]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多