出现了AttributeError: 'NoneType' object has no attribute 'text'该怎么修改这些代码
时间: 2023-06-23 13:02:06 浏览: 616
这个错误通常是因为 BeautifulSoup 没有找到指定的 HTML 元素,导致返回值是 None
,而 None
没有 text
属性,所以会抛出 AttributeError
。你可以添加一些针对性的判断来避免这个错误,以下是修改后的代码:
import requests
from bs4 import BeautifulSoup
import re
import pandas as pd
url = 'https://music.163.com/discover/toplist?id=19723756'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
song_list = soup.find('ul', {'class': 'f-hide'})
song_items = song_list.find_all('li')
data = []
for song_item in song_items:
song_title = song_item.find('a')
if song_title:
song_title = song_title.text.strip()
else:
song_title = ''
song_id = song_item.find('a')
if song_id:
song_id = song_id['href'].split('=')[1]
else:
song_id = ''
song_url = f'https://music.163.com/song/media/outer/url?id={song_id}.mp3'
song_artists = song_item.find('span', {'class': 's-fc3'})
if song_artists:
song_artists = song_artists.text.strip()
song_artists = re.sub('\s+', ' ', song_artists)
song_artists = re.sub('/', ', ', song_artists)
else:
song_artists = ''
data.append([song_title, song_url, song_artists])
df = pd.DataFrame(data, columns=['Title', 'URL', 'Artists'])
df.to_excel('song_list.xlsx', index=False)
修改后的代码在查找 HTML 元素时,增加了对返回值是否为 None
的判断,避免了出现 AttributeError
异常。
相关推荐



















