python - 指定元素和类名后,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
[]
解决方案
我认为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()
,但出于演示目的,这应该足够了。)
推荐阅读
- python - ValueError:y_true 中只有一个类。在这种情况下没有定义 ROC AUC 分数
- typescript - Live-server 无法运行打字稿?
- javascript - Observable 内部的异步/等待
- php - 如果使用 MySQL IN 语句从数组中找不到匹配项,则返回 0
- php - 如何使循环更快?
- php - JSON 代码到数组 - 引号和双引号
- c# - Unity Photon - 如何同步玩家统计/信息
- javascript - javascript从html字符串生成pdf
- android - 在 EditText 中禁用字典建议、退格和删除单词或句子
- kubernetes - Nginx Ingress 服务失败