python - 如何从 python beautiful soup 的表中获取 tbody?

标签 python web-scraping beautifulsoup

我正在尝试从“决赛比赛列表”表(第二张表)中删除 Year & Winners(第一列和第二列) http://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_finals :我正在使用下面的代码:

import urllib2
from BeautifulSoup import BeautifulSoup

url = "http://www.samhsa.gov/data/NSDUH/2k10State/NSDUHsae2010/NSDUHsaeAppC2010.htm"
soup = BeautifulSoup(urllib2.urlopen(url).read())
soup.findAll('table')[0].tbody.findAll('tr')
for row in soup.findAll('table')[0].tbody.findAll('tr'):
    first_column = row.findAll('th')[0].contents
    third_column = row.findAll('td')[2].contents
    print first_column, third_column

使用上面的代码,我能够很好地获得第一列和第三列。但是当我对 http://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_finals 使用相同的代码时,它找不到 tbody 作为它的元素,但是当我检查元素时我可以看到 tbody。

url = "http://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_finals"
soup = BeautifulSoup(urllib2.urlopen(url).read())

print soup.findAll('table')[2]

    soup.findAll('table')[2].tbody.findAll('tr')
    for row in soup.findAll('table')[0].tbody.findAll('tr'):
        first_column = row.findAll('th')[0].contents
        third_column = row.findAll('td')[2].contents
        print first_column, third_column

这是我从评论错误中得到的:

'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-150-fedd08c6da16> in <module>()
      7 # print soup.findAll('table')[2]
      8 
----> 9 soup.findAll('table')[2].tbody.findAll('tr')
     10 for row in soup.findAll('table')[0].tbody.findAll('tr'):
     11     first_column = row.findAll('th')[0].contents

AttributeError: 'NoneType' object has no attribute 'findAll'

'

最佳答案

如果您通过浏览器中的检查工具进行检查,它将插入 tbody 标签。

源代码可能包含也可能不包含它们。如果您真的想知道,我建议您查看源代码 View 。

无论哪种方式,您都不需要遍历到 tbody,只需:

soup.findAll('table')[0].findAll('tr') 应该可以。

关于python - 如何从 python beautiful soup 的表中获取 tbody?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20522820/

相关文章:

python - 如何裁剪图像,如果坐标不存在,则延伸另一侧,从而保持裁剪的大小相同?

python - 使用请求和 BeautifulSoup 下载文件

Python Array 是只读的,不能追加值

python-3.x - 美丽的刮汤

python - 需要帮助来模拟 xhr 请求

python,lxml检索列表中的所有元素

python - 使用 BeautifulSoup 翻译 XLIFF 文件

python-3.x - 无法将网络抓取输出作为字典返回

python - Selenium 无效参数异常

python - 如何从列表中随机选择一个英文单词