用python编写一个selenium脚本爬取网易云音乐排名前100的歌曲
时间: 2024-04-15 21:28:54 浏览: 174
当然可以!下面是一个基本的Python脚本,使用Selenium库来爬取网易云音乐排名前100的歌曲:
```python
from selenium import webdriver
# 创建一个Chrome览器实例
driver = webdriver.Chrome()
# 打开网易云音乐排行榜页面
driver.get('https://music.163.com/#/discover/toplist?id=3779629')
# 切换到iframe内嵌页面
driver.switch_to.frame('contentFrame')
# 定位到歌曲列表
song_list = driver.find_elements_by_xpath('//tbody/tr')
# 遍历歌曲列表并输出歌曲名和歌手名
for song in song_list:
song_name = song.find_element_by_xpath('./td[2]/div/div/div/span/a/b').get_attribute('title')
artist_name = song.find_element_by_xpath('./td[4]/div/div/div/span').get_attribute('title')
print("歌曲名:", song_name)
print("歌手名:", artist_name)
print("--------------------")
# 关闭浏览器实例
driver.quit()
```
这个脚本首先创建了一个Chrome浏览器实例,然后打开网易云音乐排行榜页面。接下来,切换到内嵌的iframe页面,定位到歌曲列表,并使用XPath表达式获取每首歌曲的名称和歌手名称。最后,遍历歌曲列表并输出结果。
请确保已经安装了Selenium库,并且根据需要选择合适的浏览器驱动。在这个例子中,使用了Chrome浏览器和对应的Chrome驱动。
阅读全文
相关推荐















