Python错误:“NoneType”对象没有属性“find_all”

2023-11-22

我正在改编一个网络抓取程序,http://danielfrg.com/blog/2013/04/01/nba-scraping-data/#disqus_thread,将 ESPN 的棒球数据抓取到 CSV 中。但是,当我运行第二段代码来编写游戏的 csv 时,我从以下代码部分中得到“NoneType”对象没有属性“find_all”错误

for index, row in teams.iterrows():
    _team, url = row['team'], row['url']
    r = requests.get(BASE_URL.format(row['prefix_1'], year, row['prefix_2']))
    table = BeautifulSoup(r.text).table
    for row in table.find_all("tr")[1:]: # Remove header
        columns = row.find_all('td')
        try:
            _home = True if columns[1].li.text == 'vs' else False
            _other_team = columns[1].find_all('a')[1].text
            _score = columns[2].a.text.split(' ')[0].split('-')
            _won = True if columns[2].span.text == 'W' else False

            match_id.append(columns[2].a['href'].split('?id=')[1])
            home_team.append(_team if _home else _other_team)
            visit_team.append(_team if not _home else _other_team)
            d = datetime.strptime(columns[0].text, '%a, %b %d')
            dates.append(date(year, d.month, d.day))

我可以发布整个程序,但这是编译器读取错误的代码段。

完整的错误文本是

Traceback (most recent call last):
  File "C:\Python27\Project Files\Game Parser.py", line 23, in <module>
    for row in table.find_all("tr")[1:]: # Remove header
AttributeError: 'NoneType' object has no attribute 'find_all'

任何有关如何运行此代码的帮助将不胜感激。


该错误意味着table您正在通过执行以下操作构建的变量:

table = BeautifulSoup(r.text).table

正在返回None. And for row in table.find_all("tr")[1:]: on a None正在抛出错误。

您可以检查是否url有问题的表以您尝试访问的方式存在。您可以通过打印出来来做到这一点url由该语句构造:

BASE_URL.format(row['prefix_1'], year, row['prefix_2'])

然后在浏览器中访问此网址,检查其中是否有您感兴趣的表。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python错误:“NoneType”对象没有属性“find_all” 的相关文章

随机推荐