selenium爬取网易云歌单创作者
时间: 2023-12-04 15:41:56 浏览: 44
以下是使用Python Selenium爬取网易云音乐歌单创作者的示例代码:
```python
from selenium import webdriver
# 创建浏览器对象
browser = webdriver.Chrome()
# 打开网易云音乐歌单页面
browser.get('https://music.163.com/#/playlist?id=歌单ID')
# 切换到iframe
browser.switch_to.frame('contentFrame')
# 获取歌单创作者
creator = browser.find_element_by_css_selector('.user.f-ff2.s-fc3').text
# 输出歌单创作者
print('歌单创作者:', creator)
# 关闭浏览器
browser.quit()
```
其中,需要将代码中的“歌单ID”替换为实际的歌单ID。可以通过在网易云音乐中打开歌单页面,查看URL中的“id=”后面的数字即为歌单ID。
相关问题
python selenium 爬取网易云音乐歌单名
使用Python的Selenium库可以实现爬取网易云音乐歌单名的功能。首先,我们需要安装Selenium库,并下载对应的WebDriver,如ChromeDriver。然后按照以下步骤进行操作:
1. 导入必要的库和模块:
```python
from selenium import webdriver
import time
```
2. 创建浏览器对象并打开网易云音乐的歌单页面:
```python
url = 'https://music.163.com/#/discover/playlist/'
window = webdriver.Chrome('./chromedriver')
window.get(url)
time.sleep(1)
```
3. 切换到iframe窗口:
```python
iframe = window.find_element_by_id('g_iframe')
window.switch_to.frame(iframe)
```
4. 提取歌单名:
```python
music_list = window.find_elements_by_xpath('//ul[@class="m-cvrlst f-cb"]/li')
for music_element in music_list:
print(music_element.text)
print()
print('*'*20)
```
5. 获取下一页并继续提取歌单名,直到没有下一页为止:
```python
page = 1
while True:
time.sleep(2)
next = window.find_element_by_link_text('下一页')
if not next.get_attribute('class') == 'zbtn znxt js-disabled':
next.click()
else:
break
time.sleep(1)
music_list = window.find_elements_by_xpath('//ul[@class="m-cvrlst f-cb"]/li')
for music_element in music_list:
print(music_element.text)
print()
print(page,'*'*20)
page += 1
```
6. 退出浏览器:
```python
window.quit()
```
用selenium爬取网易云音乐歌单并且保存为csv文件
首先,你需要安装 Selenium 库,并且需要一个可以运行的浏览器驱动。下面是一个示例代码,它会爬取网易云音乐歌单的歌曲名称和歌手名称,并将这些信息保存到 CSV 文件中:
```python
# 导入必要的库
from selenium import webdriver
from selenium.webdriver.common.by import By
import csv
# 定义保存到 CSV 文件中的信息的列表
songs = []
# 使用 webdriver 启动浏览器
driver = webdriver.Firefox()
# 使用浏览器访问网易云音乐歌单的 URL
driver.get("https://music.163.com/#/playlist?id=你的歌单 ID")
# 等待页面加载完成
driver.implicitly_wait(10)
# 获取歌曲列表的 div 元素
song_list_div = driver.find_element(By.ID, "song-list-pre-cache")
# 获取所有的 li 元素
li_elements = song_list_div.find_elements(By.TAG_NAME, "li")
# 遍历所有的 li 元素
for li in li_elements:
# 获取歌曲名称和歌手名称
song_name = li.find_element(By.CLASS_NAME, "f-thide").text
artist_name = li.find_element(By.CLASS_NAME, "s-fc3").text
# 将歌曲信息添加到列表中
songs.append((song_name, artist_name))
# 关闭浏览器
driver.close()
# 将歌曲信息写入 CSV 文件中
with open("songs.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerows(songs)
```
在这段代码中,我们使用了 Selenium 的 webdriver 模块启动了 Firefox 浏