[英]Python error: 'NoneType' object has no attribute 'find_all'
[英]Python Attribute Error: 'NoneType' object has no attribute 'find_all'
我正在嘗試獲取美國各州的縮寫,但是此代碼為:
from bs4 import BeautifulSoup
from urllib.request import urlopen
url='https://simple.wikipedia.org/wiki/List_of_U.S._states'
web=urlopen(url)
source=BeautifulSoup(web, 'html.parser')
table=source.find('table', {'class': 'wikitable sortable jquery-tablesorter'})
abbs=table.find_all('b')
print(abbs.get_text())
返回AttributeError:'Nonetype'對象沒有屬性'find_all'。 我的代碼有什么問題?
干得好。
我將source.find中的類更改為'wikitable sortable'
。 另外,方法abbs.get_text()
給了我一個錯誤,所以我只是使用了生成器函數來獲取想要的文本。
from bs4 import BeautifulSoup
from urllib.request import urlopen
web = urlopen('https://simple.wikipedia.org/wiki/List_of_U.S._states')
source = BeautifulSoup(web, 'lxml')
table = source.find(class_='wikitable sortable').find_all('b')
b_arr = '\n'.join([x.text for x in table])
print(b_arr)
部分輸出:
AL
AK
AZ
AR
CA
CO
正如Patrick所說,
source.first()僅返回第一個元素。
first()方法的源代碼供參考:
def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs):
"""Return only the first child of this Tag matching the given criteria."""
r = None
l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
findChild = find
提取表后,它的類名是wikitable sortable
。
因此,按照上面的代碼,它返回None
。
因此,您可能希望將代碼更改為...
from bs4 import BeautifulSoup
from urllib.request import urlopen
url = 'https://simple.wikipedia.org/wiki/List_of_U.S._states'
web = urlopen(url)
source = BeautifulSoup(web, 'html.parser')
table = source.find('table', class_='wikitable')
abbs = table.find_all('b')
abbs_list = [i.get_text().strip() for i in abbs]
print(abbs_list)
希望它能回答您的問題。 :)
如注釋中所建議,URL處的HTML沒有帶有該類的表
'wikitable sortable jquery-tablesorter'
但實際上是
'wikitable sortable'
同樣,一旦您應用find_all,它就會返回一個包含所有標簽的列表,因此您不能直接將get_text()應用於它。 您可以使用列表理解來去除列表中每個元素的文本。 這是適合您問題的代碼
from bs4 import BeautifulSoup
from urllib.request import urlopen
url='https://simple.wikipedia.org/wiki/List_of_U.S._states'
web=urlopen(url)
source=BeautifulSoup(web, 'html.parser')
table=source.find('table', {'class': 'wikitable sortable'})
abbs=table.find_all('b')
values = [ele.text.strip() for ele in abbs]
print(values)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.