Python Attribute 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())

returns AttributeError:'Nonetype' 对象没有属性 'find_all'。我的代码有什么问题?

给你。

我将 source.find 中的 class 更改为 '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

按照的建议,

source.first() returns只有第一个元素。

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

提取后 table 它 class 名称为 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 没有 table 和 class

'wikitable sortable jquery-tablesorter'

但 class 实际上是

'wikitable sortable'

此外,一旦您应用 find_all,它 returns 一个包含所有标签的列表,因此您不能直接对其应用 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)