pandas 属性错误:'NoneType'对象在抓取数据表数据时没有属性'find_all'

kb5ga3dv  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(307)

我当前无法理解以下错误:
for i in table.find_all('tr'):
它引用了以下代码的第21行:

import pandas as pd
import requests
from bs4 import BeautifulSoup

url = 'https://www.dwd.de/DE/wetter/wetterundklima_vorort/hessen/offenbach/_node.html'

page = requests.get(url)

soup = BeautifulSoup(page.text, 'lxml')
soup

# obtain information from html tag <table>

table = soup.find('table', id='wetklitab')
table

# obtain information from html tag <tr>

headers = []
for i in table.find_all('tr'):
    title = i.text
    headers.append(title)
    print(f"{title}")

这是for i in table.find_all('tr'):,谁能解释一下这个错误,以及如何解决它?谢谢。

kkih6yb8

kkih6yb81#

您的错误是因为tablesoup.find行之后是None。您可以通过测试table is None来确认这一点,它将为您提供True。原因是您要查找的表实际上没有id。相反,它位于具有这样一个id的div标记下。
下面是代码的快速修复。

import requests
from bs4 import BeautifulSoup

url = 'https://www.dwd.de/DE/wetter/wetterundklima_vorort/hessen/offenbach/_node.html'

page = requests.get(url)

soup = BeautifulSoup(page.text, 'lxml')
soup

# obtain information from html tag <table>

div_ele = soup.find('div', id='wetklitab')
table = div_ele.find('table')
table

# obtain information from html tag <tr>

headers = []
for i in table.find_all('tr'):
    title = i.text
    headers.append(title)
    print(f"{title}")

相关问题