Python 属性错误:“NoneType”对象没有属性“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’。我的代码有什么问题?

原文由 Roy Kim 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 786
2 个回答

正如评论中所建议的,网址中的 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)

原文由 Akshay 发布,翻译遵循 CC BY-SA 3.0 许可协议

正如 帕特里克 建议的那样,

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)

我希望它能回答你的问题。 :)

原文由 Mohsin 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题