python - 用beautifulsoup从天才歌词中获取歌曲歌词│python 3.8
问题描述
我正在尝试使用 beautifulsoup 从天才歌词中获取歌曲的歌词,但是在尝试打印歌词时,我没有得到任何输出。这是我的代码:
import requests
from bs4 import BeautifulSoup
songURL = requests.get("https://genius.com/Marshmello-and-bastille-happier-lyrics")
song = songURL.content
soup = BeautifulSoup(song, 'lxml')
lyrics = soup.find_all("section")
for lyr in lyrics:
for lyr1 in lyrics.select("p"):
print(lyr1.text)
为什么这不起作用,有人可以调查一下,因为我一直在尝试这样做一段时间。
解决方案
似乎服务器返回了页面的两个版本:在一个版本中,标签带有class="song_body-lyrics"
,在另一个版本中带有class="Lyrics__Container..."
。
此脚本尝试处理这两种情况:
import requests
from bs4 import BeautifulSoup
url = 'https://genius.com/Marshmello-and-bastille-happier-lyrics'
soup = BeautifulSoup(requests.get(url).content, 'lxml')
for tag in soup.select('div[class^="Lyrics__Container"], .song_body-lyrics p'):
t = tag.get_text(strip=True, separator='\n')
if t:
print(t)
印刷:
[Intro]
Lately, I've been, I've been thinking
I want you to be happier, I want you to be happier
[Verse 1]
...and so on.
推荐阅读
- node.js - 如何用 2 个值编写 Mongoose 查找过滤器
- android - 插页式广告
- sql - 第 6 行的错误 1054 (42S22):“有子句”中的未知列“SCORE”
- sql - 使用谷歌大查询来计算在 3 个特定列上匹配的不同行数
- c# - 如何在 C# 中更新 DataGridView 单元格
- ios - SwiftUI 结合 Debounce TextField
- c++ - 构造函数中的部分模板推导
- javascript - 向机器人发送一个命令,该机器人发送一条被编辑的消息
- c - 为什么在回调函数指针时出现 EXC_BAD_ACCESS (code=EXC_I386_GPFLT)?
- c++ - 在哪里定义回调函数以便调用对象仍在范围内?