【问题标题】:select a specific set of cell under a set of tables using python and beautifulsoup使用python和beautifulsoup在一组表格下选择一组特定的单元格
【发布时间】:2015-04-08 21:24:07
【问题描述】:
  1. 假设有 N 个网页。
  2. 每个网页都有一个或多个表格。表的共同点是它们的类是相同的,考虑“table_class”。
  3. 我们需要每个表的同一列[第三列,标题为标题]下的内容。
  4. 内容含义,第三列所有行的href链接。
  5. 有些行可能只是纯文本,有些行中可能包含 href 链接。
  6. 您应该在单独的一行中打印每个 href 链接,一个接一个。

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

你是怎么编码的?

考虑网页的这两个链接:

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()

【问题讨论】:

  • 更容易理解的是有一个示例输入 HTML 和所需的输出。
  • 我不需要学习你的功课,你不告诉我们你已经做了什么。
  • @alecxe,希望这会有所帮助。
  • @PepperoniPizza 添加。我还有 7 个其他代码,但没有一个能满足我的需要,所以没有添加任何代码。

标签: python html parsing beautifulsoup


【解决方案1】:

这个想法是用wikitable 类迭代每个table;对于每个table 直接在i 标签内直接在td 内直接在tr 内查找链接:

import 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
------

【讨论】:

  • 请问如何选择第一个'i'或第一个'a'并仅打印它们,因为使用我的其他代码,它正在从其他td打印“a”中的所有其他内容.
  • @bsy 这里的关键技巧是使用 i 元素 - 如果你看到,只有标题列的内容是斜体。
  • 哇,太棒了。所以我今天学会了观察非常微小的事情。感谢您的精彩解释。
猜你喜欢
  • 2022-08-20
  • 1970-01-01
  • 1970-01-01
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
相关资源
最近更新 更多