Python爬取网易云音乐
时间: 2023-11-29 10:46:01 浏览: 153
以下是使用Python爬取网易云音乐的方法:
1.使用requests模块获取网页源代码
```python
import requests
url = 'https://music.163.com/discover/toplist?id=3778678'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
html = response.text
```
2.使用BeautifulSoup解析网页源代码,获取歌曲id
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
song_list = soup.find('ul', {'class': 'f-hide'}).find_all('a')
for song in song_list:
print(song.text, song['href'])
song_id = song['href'].split('=')[-1]
```
3.使用selenium模块模拟浏览器操作,获取歌曲外链地址
```python
from selenium import webdriver
driver = webdriver.Chrome()
url = 'http://music.163.com/song/media/outer/url?id=' + song_id + '.mp3'
driver.get(url)
iframe = driver.find_element_by_xpath('//iframe')
driver.switch_to.frame(iframe)
audio_url = driver.find_element_by_xpath('//audio').get_attribute('src')
print(audio_url)
driver.quit()
```
阅读全文