繁体   English   中英

AttributeError:'NoneType'对象没有属性'text'-Python,BeautifulSoup错误

[英]AttributeError: 'NoneType' object has no attribute 'text' - Python , BeautifulSoup Error

我刚刚开始了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

任何帮助将不胜感激

问题是标记名称,属性名称和属性值中包含多余的空格字符 ,请替换:

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打印。

您也可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM