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

Python新手在这里. Python 2.7和beautifulsoup 4.

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

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]

这给出了一个错误,即行是列表超出索引.

所以:

>首先findAll(‘table’)-作品
>第二个findAll(‘tr’)-作品
>第三findAll(‘td’)-仅在ALL []是数字而不是变量的情况下有效.

例如

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

上面的作品是特定参考,但不是通过变量.
但是我需要在循环中获取完整的列.

解决方法:

我看了一下,表中的第一行实际上是标题,因此在第一行下面有一些内容,这应该可以工作:

>>> 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]')
上一篇:python正则表达式findall()方法匹配(个人笔记)


下一篇:正则