【问题标题】:AttributeError: 'NoneType' object has no attribute 'text' - Python , BeautifulSoup ErrorAttributeError:“NoneType”对象没有属性“文本”-Python,BeautifulSoup 错误
【发布时间】:2016-12-25 04:44:26
【问题描述】:

我刚刚开始了一个 python 网络课程,我试图使用 BeautifulSoup 解析 HTML 数据,我遇到了这个错误。我进行了研究,但找不到任何精确和确定的解决方案。所以这是一段代码:

   import requests
   from bs4 import BeautifulSoup

   request = requests.get("http://www.johnlewis.com/toms-berkley-slipper-grey/p3061099")
   content = request.content
   soup = BeautifulSoup(content, 'html.parser')
   element = soup.find(" span", {"itemprop ": "price ", "class": "now-price"})
   string_price = (element.text.strip())
   print(int(string_price))


  # <span itemprop="price" class="now-price"> £40.00 </span>

这是我面临的错误:

   C:\Users\IngeniousAmbivert\venv\Scripts\python.exe 

   C:/Users/IngeniousAmbivert/PycharmProjects/FullStack/price-eg/src/app.py

    Traceback (most recent call last):
         File "C:/Users/IngeniousAmbivert/PycharmProjects/FullStack/price-eg/src/app.py", line 8, in <module>
             string_price = (element.text.strip())
    AttributeError: 'NoneType' object has no attribute 'text'

 Process finished with exit code 1

任何帮助将不胜感激

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    问题是标签名、属性名和属性值里面的多余的空格字符,替换:

    element = soup.find(" span", {"itemprop ": "price ", "class": "now-price"})
    

    与:

    element = soup.find("span", {"itemprop": "price", "class": "now-price"})
    

    之后,在转换字符串时要修复两件事:

    • 从左边去掉£ 字符
    • 使用float() 而不是int()

    固定版本:

    element = soup.find("span", {"itemprop": "price", "class": "now-price"})
    string_price = (element.get_text(strip=True).lstrip("£"))
    print(float(string_price))
    

    你会看到 40.00 打印出来。

    【讨论】:

    • 谢谢伙计。它运作良好。但是,如果您能详细说明代码,那就太好了。因为正如我提到的,我是 python 的新手,我无法理解这个语句 :string_price = (element.get_text(strip=True).lstrip("£")) 。谢谢
    • @user7338971 绝对。 .get_text(strip=True) 有助于获取元素的文本并去除文本周围所有额外的换行符和空格 - 通常你会通过 .strip() 来完成,但 bs4 有这个接受 strip 参数的 get_text() 方法 -很方便。之后,我们去掉了英镑符号。希望这能让事情更清楚。
    • 我真的很感激。谢谢你的帮助 。我很感激。
    【解决方案2】:

    您也可以使用 css 选择器尝试这样的操作:

    import requests
    from bs4 import BeautifulSoup
    
    request = requests.get("http://www.johnlewis.com/toms-berkley-slipper-grey/p3061099")
    content = request.content
    soup = BeautifulSoup(content, 'html.parser')
    # print soup
    element = soup.select("div p.price span.now-price")[0]
    print element
    string_price = (element.text.strip())
    print(int(float(string_price[1:])))
    

    输出:

    <span class="now-price" itemprop="price">
                                                £40.00
                                                    </span>
    40
    

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      相关资源
      最近更新 更多