首页 > 解决方案 > 指定元素和类名后,BeautifulSoup 没有针对任何内容

问题描述

我正在尝试抓取这个网站https://en.wikipedia.org/wiki/Korean_drama。特别是有线电视收视率最高的韩剧名单。这就是检查元素的样子在此处输入图像描述

这是我的代码

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
[]

标签: pythonpython-3.xbeautifulsouplxml

解决方案


我认为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(),但出于演示目的,这应该足够了。)


推荐阅读