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

标签 python html parsing beautifulsoup

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

最佳答案

这个想法是使用 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
------

关于python - 使用 python 和 beautifulsoup 选择一组表格下的一组特定单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29525613/

相关文章:

python - 将 Keras 转换为 TensorFlow——剪枝+概率

iPhone - removeObjectIdenticalTo 行为

parsing - Prolog 中的定子句语法 - Or 语句

python - Django - ManyToManyField 未显示在表单中

python - 修复不显示两个值的 python 代码

html - 均衡左右div的高度,防止右div低于左div

javascript - 添加验证以在用户忘记某个值并收到第二个和第三个值为空的错误时通知用户

JavaScript 阻止滚动

parsing - Prolog - 带有文件输入的 DCG 解析器

python - 如何读取一个大的二进制文件并通过一些标记拆分其内容