liyifeng295641 发表于 2024-1-2 15:05:17

python爬虫02(朋友实训项目)

本帖最后由 liyifeng295641 于 2024-1-3 16:09 编辑

用豆瓣音乐网爬取https://music.douban.com/tag/%E6%B5%81%E8%A1%8C 豆瓣音乐标签:流行
数据量大于110个,最终数据保存Excel,Excel表格要有表头 爬取内容行数×列数>110

FishC 发表于 2024-1-2 15:05:35

可以使用Python的爬虫库`BeautifulSoup`和`requests`来实现这个爬虫任务。

首先,我们需要导入必要的库:

import requests
from bs4 import BeautifulSoup
import pandas as pd

接下来,我们可以通过发送HTTP请求获取网页的源代码,并使用`BeautifulSoup`解析HTML:

url = 'https://music.douban.com/tag/%E6%B5%81%E8%A1%8C'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

然后,我们可以使用`BeautifulSoup`提供的方法来定位需要的数据。例如,在豆瓣音乐标签页面上,每个歌曲都包含在一个`div`元素中,其类名为`music-item`。我们可以使用`.find_all()`方法来获取所有的歌曲元素:

songs = soup.find_all('div', class_='music-item')

接下来,我们可以遍历每个歌曲元素,提取所需的信息,例如歌曲名称、艺术家和评分等。以歌曲名称和艺术家为例,它们通常位于歌曲元素中的特定标签内(如`<a>`或`<h3>`):

data = []
for song in songs:
    name = song.find('a', class_='title').text.strip()
    artist = song.find('h3', class_='artist').text.strip()
    data.append()

最后,我们可以使用`pandas`库将数据保存到Excel表格中,确保表格具有表头:

df = pd.DataFrame(data, columns=['歌曲名称', '艺术家'])
df.to_excel('douban_music.xlsx', index=False)

完整的代码示例:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://music.douban.com/tag/%E6%B5%81%E8%A1%8C'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

songs = soup.find_all('div', class_='music-item')

data = []
for song in songs:
    name = song.find('a', class_='title').text.strip()
    artist = song.find('h3', class_='artist').text.strip()
    data.append()

df = pd.DataFrame(data, columns=['歌曲名称', '艺术家'])
df.to_excel('douban_music.xlsx', index=False)

这样,你就可以运行以上代码,爬取豆瓣音乐标签为“流行”的所有歌曲,并保存到名为"douban_music.xlsx"的Excel表格中了。注意,你可能需要安装`BeautifulSoup`和`pandas`库,你可以使用`pip`命令进行安装。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: python爬虫02(朋友实训项目)