在指定元素和类名后,BeautifulSoup不会定位任何内容

问题描述

我正在尝试抓取该网站https://en.wikipedia.org/wiki/Korean_drama。特别是有线电视收视率最高的韩国戏剧列表。这就是检查元素的外观

enter image description here

这是我的代码

import requests
from bs4 import BeautifulSoup

url = 'https://en.wikipedia.org/wiki/Korean_drama'
response = requests.get(url)
soup = BeautifulSoup(response.text,'lxml')
kdramas = soup.find_all(
    'table',class_="wikitable sortable jquery-tablesorter")
print(kdramas)
for kdrama in kdramas:
    print(kdrama.text)

这是我运行代码时发生的情况

admins-MBP:~ admin$ python3 kdramas.py
[]

解决方法

我认为jquery-tablesorter类可以动态添加,这就是为什么BeautifulSoup不会读取它的原因。

我的建议是选择引入表的h3标记,然后在DOM中挖掘第一个表对象。

类似的东西:

# h3 tag name is actually in a <span> inside the h3 element
table_lead_in = soup.find('span',id="List_of_highest-rated_Korean_dramas_in_public_broadcast")

for drama_table in table_lead_in.find_next('tbody'):
    for tr in drama_table.find_all_next('tr'):
        rank = tr.find('td').text
        title = tr.find('a').text
        print(f"Title: {title} ** Rank: {rank}")

输出:

Title: You and I ** Rank: 1
Title: First Love ** Rank: 2
Title: What Is Love ** Rank: 3
Title: Sandglass ** Rank: 4
Title: Hur Jun ** Rank: 5
Title: A Sunny Place of the Young ** Rank: 6
Title: Sons and Daughters ** Rank: 7

(注意:find()调用中有一些惰性假设,但是出于演示目的,这已经足够。)

,

我发现指定的代码没有问题。

我的建议是尝试将其他标签放在层次结构中更高的位置并观察输出。不同的站点具有不同的标记和类,因此没有一个解决所有解决方案。也许首先尝试将div标签放在层次结构中较高的位置。

,

wikitable sortable jquery-tablesorter有时被命名为wikitable sortable。 您可以使用CSS选择器选择以wikitable sortable开头的类,无论哪种情况都可以使用:

import requests
from bs4 import BeautifulSoup

url = 'https://en.wikipedia.org/wiki/Korean_drama'

response = requests.get(url)
soup = BeautifulSoup(response.text,'lxml')
kdramas = soup.select_one('table[class^="wikitable sortable"]:nth-of-type(2)')

for row in kdramas.select('tr'):
    data = [td.get_text(strip=True) for td in row.select('td')]
    print(' '.join('{: <30}'.format(d) for d in data))

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...