2016-12-25 148 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 
相關問題