Python BeautifulSoup从表中获取列 - IndexError列表索引超出范围

时间:2014-02-01 04:31:44

标签: python html-parsing beautifulsoup findall

Python新手在这里。 Python 2.7 with 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. third findAll('td') - 仅当ALL []是数字而不是变量时才有效。
  4. e.g。

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

    以上工作原理,因为它是特定参考,但不是通过变量。 但我需要在循环中获取完整列。

1 个答案:

答案 0 :(得分:0)

我看一下,表中的第一行实际上是一个标题,所以在第一个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]')