python selenium 爬取网易云音乐歌单名
时间: 2023-10-19 10:09:12 浏览: 209
详解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()
```
阅读全文