在python中抓取html表格

用户5994246

我想用这个代码刮一个 html 表

import requests
from bs4 import BeautifulSoup

page1 = requests.get("http://kworb.net/spotify/country/br_weekly.html")                                                  
soup = BeautifulSoup(page1.content, 'html.parser')
for tr in soup.findAll('tr'):
    tds =tr.find_all('td')
    print(tds[0].text)

它似乎有效:我能够在不同的 tds 列表中获取表格及其每一行。除了当我尝试获取每一行的第一列 (tds[0].text) 时,出现错误。

你能提供一些线索吗?

简单的

第一行有标题<th>而不是<td>所以你变空tds- 你必须检查大小tds

if len(tds) > 0:
    print(tds[0].text)

或更短

if tds:
    print(tds[0].text)

或者您可以使用跳过第一行 [1:]

for tr in soup.find_all('tr')[1:]:
   tds = tr.find_all('td')
   print(tds[0].text)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章