|
发表于 2024-5-29 09:41:25
|
显示全部楼层
非常抱歉,前面的回答中给出的代码依然存在问题。`on_bad_lines`参数已不再支持。
以下是修复后的代码:
- from bs4 import BeautifulSoup
- import pandas as pd
- import requests
- import time
- def get_data_of_music_list_detail_page():
- df = pd.read_csv('music_data/new/music_list.csv', header=None, names=['url'], sep=',')
- headers = {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
- }
- print("正在获取歌单详情页的信息...")
- for i, row in df.iterrows():
- url = 'https://music.163.com' + row['url']
- response = requests.get(url=url, headers=headers)
- html = response.text
- soup = BeautifulSoup(html, 'html.parser')
- # 获取歌单标题
- title = soup.select('h2')[0].get_text().replace(',', ',')
- # 获取标签
- tags = []
- tags_message = soup.select('.u-tag i')
- for p in tags_message:
- tags.append(p.get_text())
- # 对标签进行格式化
- if len(tags) > 1:
- tag = '-'.join(tags)
- else:
- tag = tags[0] if tags else ''
- # 获取歌单介绍
- desc_element = soup.select('#album-desc-more')
- text = desc_element[0].get_text().replace('\n', '').replace(',', ',') if desc_element else '无'
- # 获取歌单收藏量
- collection = soup.select('#content-operation i')[0].get_text().replace('(', '').replace(')', '')
- # 歌单播放量
- play = soup.select('.s-fc6')[0].get_text()
- # 歌单内歌曲数
- songs = soup.select('#playlist-track-count')[0].get_text()
- # 歌单评论数
- comments = soup.select('#cnt_comment_count')[0].get_text()
- # 输出歌单详情页信息
- print(title, tag, text, collection, play, songs, comments)
- # 将详情页信息写入CSV文件中
- with open('music_data/new/music_detail.csv', 'a+', encoding='utf-8-sig') as f:
- f.write(f"{title},{tag},{text},{collection},{play},{songs},{comments}\n")
- # 获取歌单内歌曲名称
- li = soup.select('.f-hide li a')
- with open('music_data/new/music_name.csv', 'a+', encoding='utf-8-sig') as f:
- for j in li:
- f.write(j.get_text() + '\n')
- print("已获取歌单详情页的信息,保存至 music_data/music_name.csv")
复制代码
请确保已经将`music_data/new/music_list.csv`文件正确准备,并检查文件路径是否正确。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|