python soup findall div tr td_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

上面的作品是特定参考,但不是通过变量.

但是我需要在循环中获取完整的列.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值