2017-07-10 155 views
-6

Python代碼截圖捕捉「NoneType」對象有沒有屬性「串」

什麼事?關於它?

html = """ <html><body>(html)(body) 
<h1>(h1)what is the scraping(/h1)</h1> 
<p>(p)To analyze a web page(/p)</p> 
<p>(p)To extract the desired part(/p)</p> 
(/body)(/html)</body></html> """ 

soup = BeautifulSoup(html, 'html.parser') 

title = soup.find(id="title") 

body = soup.find(id="body") 

print ("title=" + title.string) 

print ("body=" + body.string) 
+1

您需要正確格式化代碼並給我們一個問題來回答。 –

+0

你的'soup.find'調用都返回None。下一次,您需要包含錯誤的完整追溯。此外,解釋你的代碼應該做什麼以及你期望的。 – idjaw

+1

可能重複的[Python:屬性錯誤 - 'NoneType'對象沒有屬性'東西'](https://stackoverflow.com/questions/8949252/python-attribute-error-nonetype-object-has-no-attribute-東西) –

回答

0

。在你沒有html標籤title。所以,title=None。因此你無法從中得到任何內容。

嘗試用lxml代替html.parser並嘗試soup.body而不是搜索body標籤。

+0

'soup.find(id =「body」)'也返回'None'。 – idjaw

+0

嘗試soup.body而不是find(body),並嘗試用lxml代替html.parser –

+0

我不是問題提問者。我在說代碼中有另一個錯誤,所以你可以將它添加到你的答案中。讓你的答案更完整。 – idjaw

1

您正在嘗試查找id等於title的元素,如<p id="title">foo bar</p>

如果您想通過其類型找到標籤,這樣做:

soup.find('body') # returns content of <body> 

或者

soup.find('title') 

第二個例子將不會在你的情況下工作,因爲在你的HTML沒有<title>foo bar</title>標籤,但你明白了。

相關問題