使用python和beautifulsoup在一组表下选择一组特定的单元格

时间:2015-04-08 21:24:07

标签: python html parsing beautifulsoup

  1. 考虑有N个网页。
  2. 每个网页都有一个或多个表格。表格的共同点是它们的类是相同的,考虑" table_class。"
  3. 我们需要每个表格的同一栏[第三栏,标题是标题]下的内容。
  4. 内容含义,href在所有行的第三列中链接。
  5. 有些行可能只是纯文本,有些行可能有href链接。
  6. 您应该在一个接一个的单独行中打印每个href链接。

  7. 使用属性进行过滤无效,因为某些标记具有不同的属性。单元格的位置是唯一可用的提示。

  8. 你如何编码?

    考虑网页的这两个链接:

    http://en.wikipedia.org/wiki/List_of_Telugu_films_of_2014 http://en.wikipedia.org/wiki/List_of_Telugu_films_of_2013

    考虑表:wikitable

    必填内容:列标题

    的href链接

    我试过一页代码:

    from urllib.request import urlopen
    from bs4 import BeautifulSoup, SoupStrainer
    
    
    content = urlopen("http://en.wikipedia.org/wiki/List_of_Telugu_films_of_2015").read()  
    filter_tag = SoupStrainer("table", {"class":"wikitable"})
    soup = BeautifulSoup(content, parse_only=filter_tag)
    
    for sp in soup.find_all('tr'):
        for bt in sp.find_all('td'):
            for link in bt.find_all('a'):
                print(link.get("href"))
        print()
    

1 个答案:

答案 0 :(得分:1)

我们的想法是使用table类迭代每个wikitable;对于每个table直接在i内直接位于tdtrimport requests from bs4 import BeautifulSoup url = "http://en.wikipedia.org/wiki/List_of_Telugu_films_of_2014" soup = BeautifulSoup(requests.get(url).content) # iterate over tables for table in soup.select('table.wikitable.sortable'): # get the table header/description, continue if not found h3 = table.find_previous_sibling('h3') if h3 is None: continue print h3.text # get the links for link in table.select('tr > td > i > a'): print link.text, "|", link.get('href', '') print "------" 内找到链接:

January 2014–june 2014[edit]
Celebrity | /wiki/Celebrity
Kshatriya | /wiki/Kshatriya
1: Nenokkadine | /wiki/1:_Nenokkadine
...
Oohalu Gusagusalade | /wiki/Oohalu_Gusagusalade
Autonagar Surya | /wiki/Autonagar_Surya
------
July 2014 – December 2014[edit]
...
O Manishi Katha | /wiki/O_Manishi_Katha
Mukunda | /wiki/Mukunda
Chinnadana Nee Kosam | /wiki/Chinnadana_Nee_Kosam
------

打印(为清晰起见,还打印表格名称):

{{1}}