【发布时间】: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]
它给出了一个错误,即行是一个超出索引的列表。
所以:
- 首先 findAll('table') - 有效
- 第二个 findAll('tr') - 有效
- 第三个 findAll('td') - 仅当 ALL [ ] 是数字而不是变量时才有效。
例如
print soup.findAll('table')[8].findAll('tr')[2].findAll('td')[2].contents
上面的工作是因为它是特定的参考,而不是通过变量。 但我需要它在一个循环内获得完整的列。
【问题讨论】:
标签: python html-parsing beautifulsoup findall