python - 抓取 html 表 - python

标签 python web-scraping beautifulsoup html-table html-parsing

我在从 html 中抓取表格时遇到问题。实际上它是一张更大的 table 里面有三张 table 。我正在使用 BS4,它工作得很好,直到找到所有“td”标签,但是当我尝试打印我需要的信息时,程序在第一个表的末尾停止并显示此错误消息:

"IndexError: list index out of range"

import re
import urllib2
from bs4 import BeautifulSoup

url = 'http://trackinfo.com/entries-alphabetical.jsp?raceid13=GBR$20140314A'
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)


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

有什么解决办法吗?

最佳答案

通过查看您的代码,在循环中假设在找到的 tr 元素列表中始终有(至少)2 个 td 元素。如果在某些情况下 tr 元素包含的元素少于 2 个,则会引发 IndexError。

尝试将循环更改为如下所示:

for tr in soup.find_all('tr')[2:]:
  tds = tr.find_all('td')
  if len(tds) >= 2:
    print tds[0].text, tds[1].text

td 元素数量必须为 2 或更多的检查特定于您正在解析的页面,我猜您希望将两个值写在一起。更通用的解决方案可能是:

for tr in soup.find_all('tr')[2:]:
  for td in tr.find_all('td'):
    print td.text

关于python - 抓取 html 表 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22407472/

相关文章:

python - 使用 BeautifulSoup 从页面中抓取所有结果

python - 为什么我在循环 pandas 数据帧时收到此错误

python - 如何在 PDF 文档中插入 SVG 文件?

python - 从 python27 中的文件夹导入模块

python - Selenium 返回一个页面源,其中所有标签名称都以 "a0:"为前缀

excel - 使用 selenium 将文件下载到特定目录

python - Scrapy 从动态表中提取数据

python - Scrapy - 如何停止元刷新重定向?

python - BeautifulSoup 抓取无输出

python - BeautifulSoup 通过标签、属性、RegEx 和迭代扫描 HTML