2016-12-25 579 views
0

我刚开始一个python网络课程,我试图用BeautifulSoup解析HTML数据,并且遇到了这个错误。我研究过但无法找到任何确切的和确定的解决方案。因此,这里是一段代码:AttributeError:'NoneType'对象没有属性'text' - Python,BeautifulSoup错误

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 

任何帮助将不胜感激

回答

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

+0

谢谢队友。它运作良好。但是,如果你可以详细说明那些很棒的代码。因为正如我所提到的,我是一个Python新手,我无法理解这个语句:string_price =(element.get_text(strip = True).lstrip(“£”))。谢谢 –

+0

@ user7338971绝对。 '.get_text(strip = True)'有助于获取元素的文本并去除文本周围的所有额外换行符和空格 - 通常您可以通过'.strip()'来实现,但bs4具有这个'get_text )'接受'strip'参数的方法 - 非常方便。之后,我们左键去掉英镑符号。希望让事情更清楚。 – alecxe

+0

我很感激。谢谢你的帮助 。我很感激 。 –

0

你可以尝试这样也使用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 
相关问题