![](/img/trans.png)
[英]AttributeError: 'NoneType' object has no attribute 'findNext'>> when retrieving tweets
[英]Python: AttributeError: 'NoneType' object has no attribute 'findNext'
我正在嘗試使用 BeautifulSoup 抓取網站,但遇到了問題。 我正在學習在 python 2.7 中完成的教程,其中包含完全相同的代碼並且沒有任何問題。
import urllib.request
from bs4 import *
htmlfile = urllib.request.urlopen("http://en.wikipedia.org/wiki/Steve_Jobs")
htmltext = htmlfile.read()
soup = BeautifulSoup(htmltext)
title = (soup.title.text)
body = soup.find("Born").findNext('td')
print (body.text)
如果我嘗試運行我得到的程序,
Traceback (most recent call last):
File "C:\Users\USER\Documents\Python Programs\World Population.py", line 13, in <module>
body = soup.find("Born").findNext('p')
AttributeError: 'NoneType' object has no attribute 'findNext'
這是python 3的問題還是我太天真了?
find
和find_all
方法不會搜索文檔中的任意文本,而是搜索HTML 標簽。 文檔清楚地說明了這一點(我的斜體):
傳入 name 的值,您將告訴 Beautiful Soup 僅考慮具有特定名稱的標簽。 文本字符串將被忽略,名稱不匹配的標簽也將被忽略。 這是最簡單的用法:
soup.find_all("title")
# [<title>The Dormouse's story</title>]
這就是為什么您的soup.find("Born")
返回None
原因,因此它抱怨NoneType
( None
的類型)沒有findNext()
方法。
您引用的頁面包含(在撰寫此答案時)“出生”一詞的八個副本,其中沒有一個是標簽。
查看該頁面的 HTML 源代碼,您會發現最好的選擇可能是尋找正確的跨度(格式化為可讀性):
<th scope="row" style="text-align: left;">Born</th>
<td>
<span class="nickname">Steven Paul Jobs</span><br />
<span style="display: none;">(<span class="bday">1955-02-24</span>)</span>February 24, 1955<br />
</td>
find
方法查找標簽,而不是文本。 要查找姓名、生日和出生地,您必須查找具有相應類名的span
元素,並訪問該項目的text
屬性:
import urllib.request
from bs4 import *
soup = BeautifulSoup(urllib.request.urlopen("http://en.wikipedia.org/wiki/Steve_Jobs"))
title = soup.title.text
name = soup.find('span', {'class': 'nickname'}).text
bday = soup.find('span', {'class': 'bday'}).text
birthplace = soup.find('span', {'class': 'birthplace'}).text
print(name)
print(bday)
print(birthplace)
輸出:
Steven Paul Jobs
1955-02-24
San Francisco, California, US
PS:您不必在urlopen
上調用read
,BS 接受類文件對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.