ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-13 18:55:23  阅读:256  来源: 互联网

标签:python beautifulsoup html-parsing findall


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,beautifulsoup,html-parsing,findall
来源: https://codeday.me/bug/20191013/1909742.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有