首页 > 解决方案 > 使用 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')

正确返回歌曲的歌词。两个页面具有相同的布局。有人可以帮我弄清楚吗?

标签: pythonbeautifulsoupscreen-scraping

解决方案


该页面返回两个版本的 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.

推荐阅读