with 语句的使用来保存二进制文件(图片,视频,音频)

#导入必要的库
import requests
import re
from urllib.request import urlretrieve

#网址来自网易云音乐
url = "https://m8.music.126.net/20190805172142/744248b8ade6f418ebf1135918132670/ymusic/2071/e92f/f55d/40975a90886ac5a4d1ff8c2f0839a4a4.mp3"
#不同的浏览器headers不同
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3704.400 QQBrowser/10.4.3587.400'}
#方法一
# urlretrieve(url, 'D:/Users/DELL/Desktop/0.mp3')#直接用urlretrieve()函数下载即可
# print((rsq.content))  # rsq.content是得到的字节流

#方法二
rsq = requests.get(url, headers=headers)
with open('D:/Users/DELL/Desktop/1.mp3', 'wb') as f:#图片不需要encoding编码
    f.write(rsq.content)#写入字节流来保存文件

记录每一滴成长!fighting

你可能感兴趣的:(静态网页的爬取)