从网络抓取数据时遇到问题
以下提到我曾尝试过
import requests
from bs4 import BeautifulSoup
# Collect and parse first page
page = requests.get('https://www.jiosaavn.com/album/vijayashanti-birthday-telugu-hits/A05RmafpUiI_')
soup = BeautifulSoup(page.text, 'html.parser')
# Pull all text from the BodyText div
artist_name_list = soup.find(class_='song-wrap')
# Pull text from all instances of <a> tag within BodyText div
artist_name_list_items = artist_name_list.find_all('a')
for artist_name in artist_name_list_items:
print(artist_name.prettify())
我除了正确的输出
答案 0 :(得分:0)
find
如果找不到合适的元素,则返回None
。您需要先检查其返回值,然后再尝试在其上调用find_all
:
# Pull all text from the BodyText div
artist_name_list = soup.find(class_='song-wrap')
# Check that a song-wrap item was found
if artist_name_list:
# Pull text from all instances of <a> tag within BodyText div
artist_name_list_items = artist_name_list.find_all('a')
for artist_name in artist_name_list_items:
print(artist_name.prettify())