【问题标题】:how to get tbody from table from python beautiful soup ?如何从 python 美丽的汤中获取 tbody?
【发布时间】:2013-12-29 15:26:30
【问题描述】:

我正在尝试从“决赛比赛列表”表(第二个表)中删除年份和获胜者(第一和第二列) 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'

'

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:
      url = "http://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_finals"
      soup = BeautifulSoup(urllib2.urlopen(url).read())
      for tr in soup.findAll('table')[2].findAll('tr'):
          #get data
      

      然后在表格中搜索你需要的内容:)

      【讨论】:

        【解决方案3】:

        直接运行以下代码。

        tr_elements = soup.find_all('table')[2].find_all('tr')

        通过这样做,您可以访问所有&lt;tr&gt;;您将不得不使用 for 循环来执行此操作(还有其他可能的迭代方式)。不要试图找到 tbody,它是默认添加的。

        注意:

        如果在获取所需标签时遇到问题,请使用.decompose() 方法分解之前的标签。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-04-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-24
          • 2011-11-15
          • 2012-02-17
          相关资源
          最近更新 更多