python - 使用 BeautifulSoup 抓取网站时出错
问题描述
我正在尝试从天才那里收集一些歌曲。我创建了以下方法:
import requests
from bs4 import BeautifulSoup
def get_song_lyrics(link):
response = requests.get(link)
soup = BeautifulSoup(response.text, "html.parser")
lyrics = soup.find("div",attrs={'class':'lyrics'}).find("p").get_text()
return [i for i in lyrics.splitlines()]
我不明白为什么会这样
get_song_lyrics('https://genius.com/Kanye-west-black-skinhead-lyrics')
返回:
AttributeError:“NoneType”对象没有“查找”属性
而这:
get_song_lyrics('https://genius.com/Kanye-west-hold-my-liquor-lyrics')
正确返回歌曲的歌词。两个页面具有相同的布局。有人可以帮我弄清楚吗?
解决方案
该页面返回两个版本的 HTML。您可以使用此脚本来处理它们:
import requests
from bs4 import BeautifulSoup
url = 'https://genius.com/Kanye-west-black-skinhead-lyrics'
soup = BeautifulSoup(requests.get(url).content, 'lxml')
for tag in soup.select('div[class^="Lyrics__Container"], .song_body-lyrics p'):
for i in tag.select('i'):
i.unwrap()
tag.smooth()
t = tag.get_text(strip=True, separator='\n')
if t:
print(t)
印刷:
[Produced By Daft Punk & Kanye West]
[Verse 1]
For my theme song (Black)
My leather black jeans on (Black)
My by-any-means on
...and so on.
推荐阅读
- ios - 无效并重新启动后,Swift计时器将不起作用
- javascript - 循环遍历html元素中的子元素
- api - 如何在 RingCentral 沙箱中为 Outbound Fax API 创建第二个传真用户扩展?
- java - 如何制作类似于此参考的登录布局?
- postgresql - Postgres DDL 错误:'“用户”或附近的语法错误'
- laravel - 在 api 路由文件中检索标头值在 Laravel 中不起作用
- android-tv - 知道焦点在 Android TV 的最左侧视图
- python - super(subclass, class).__new__(class) 做什么?
- wordpress - How to make an input allows html tags in wordpress website
- javascript - 如何将数据库列标题名称与下拉菜单中的值匹配