【发布时间】:2021-01-26 15:09:14
【问题描述】:
我正在尝试使用 Python 和 Beautiful Soup 来抓取 Wikipedia Table。当我尝试使用 for 循环获取表列属性时,出现错误:
NameError Traceback (most recent call last)
<ipython-input-18-948408e65d8d> in <module>
1 # Header attributes of the table
2 header=[th.text.rstrip()
----> 3 for th in rows[0].find_all('th')]
4 print(header)
5 print('------------')
NameError: name 'rows' is not defined
我该如何解决这个问题?
代码:
url="https://en.wikipedia.org/wiki/List_of_municipalities_of_Norway"
发起多个 URL 请求。如果请求成功,则预期的 HTTP 响应状态代码为 200。
s=requests.Session()
response=s.get(url, timeout=10)
response
res = requests.get(url)
soup = BeautifulSoup(res.content, 'html.parser')
维基百科页面的标题
soup.title.string
找到合适的桌子来刮
right_table=soup.find('table',{"class":'sortable wikitable'})
表头属性
header=[th.text.rstrip()
for th in rows[0].find_all('th')]
print(header)
print('------------')
print(len(header))
【问题讨论】:
-
行从何而来?
-
从 right_table=soup.find('table',{"class":'sortable wikitable'})。这会从 Wikipedia 网页中找到带有 HTML 标签“sortable wikitable”的表格。我应该在 find_all 函数中调用它之前设置一个 rows=[] 吗?
-
是的。只有在初始化列表时,才能将值附加到它。
标签: python numpy beautifulsoup html-table wikipedia-api