【问题标题】:Python BeautifulSoup Getting a column from table - IndexError List index out of rangePython BeautifulSoup 从表中获取列 - IndexError 列表索引超出范围
【发布时间】:2014-02-24 23:24:01
【问题描述】:

这里是 Python 新手。 Python 2.7 和 beautifulsoup 4。

我正在尝试使用 BeautifulSoup 解析网页以获取列。网页有表格里面的表格;但表 4 是我想要的,它没有任何标题或标签。我想将数据放入列中。

from bs4 import BeautifulSoup
import urllib2

url = 'http://finance.yahoo.com/q/op?s=aapl+Options'
htmltext = urllib2.urlopen(url).read()
soup = BeautifulSoup(htmltext)

#Table 8 has the data needed; it is nested under other tables though
# specific reference works as below:
print soup.findAll('table')[8].findAll('tr')[2].findAll('td')[2].contents

# Below loop erros out:
for row in soup.findAll('table')[8].findAll('tr'):
    column2 = row.findAll('td')[2].contents
    print column2

# "Index error: list index out of range" is what I get on second line of for loop.

我在另一个示例中将此视为可行的解决方案,但对我不起作用。还尝试围绕 tr 进行迭代:

mytr = soup.findAll('table')[8].findAll('tr')

for row in mytr:
    print row.find('td') #works but gives only first td as expected
    print row.findAll('td')[2]

它给出了一个错误,即行是一个超出索引的列表。

所以:

  1. 首先 findAll('table') - 有效
  2. 第二个 findAll('tr') - 有效
  3. 第三个 findAll('td') - 仅当 ALL [ ] 是数字而不是变量时才有效。

例如

print soup.findAll('table')[8].findAll('tr')[2].findAll('td')[2].contents

上面的工作是因为它是特定的参考,而不是通过变量。 但我需要它在一个循环内获得完整的列。

【问题讨论】:

    标签: python html-parsing beautifulsoup findall


    【解决方案1】:

    我看了看,表格的第一行实际上是一个标题,所以在第一个tr 下有一些th,这应该可以:

    >>> mytr = soup.findAll('table')[9].findAll('tr')
    >>> for i,row in enumerate(mytr):
    ...     if i:
    ...         print i,row.findAll('td')[2]
    

    在大多数 html 解析的情况下,考虑一个更优雅的解决方案,比如 xml 和 xpath,比如:

    >>> from lxml import html
    >>> print html.parse(url).xpath('//table[@class="yfnc_datamodoutline1"]//td[2]')
    

    【讨论】:

    • 太好了,谢谢!我错误地查找了表 8。现在也将研究 lxml。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2017-04-05
    • 2012-07-15
    相关资源
    最近更新 更多