【Python爬虫学习-03】Requests的基本使用以及获取网易云音乐
·
- request模块介绍
- 作用:发送http网络请求,返回响应数据
- 中文文档:requests库中文文档
- 通过观察文档来学习:如何使用requests来发送网络请求
1、发送GET请求
例子:通过requests向百度首页发送请求,获取百度首页的数据
import requests # 导出需要的第三方库
# 目标url
url = 'http://www.baidu.com'
# 发送请求,用response获取返回的结果
response = requests.get(url)
# 输出请求返回的结果
print(response.text)
2、响应数据的获取
方式1:response.text
获取的是字符串
方式2:respnse.content
获取的是原始的二进制数据(bytes类型的数据),需要通过decode()方法解码为字符串类型
3、字符集编码
1、python中的两种字符串类型
- str:unicode的呈现形式
- bytes:字节类型,互联网上数据都是以二进制的方式/字节传输的
2、str和byte类型的相互转换
- str 使用encode()方式转化为bytes
s = 'abc'
print(type(s))
# str编码变为bytes类型
b = s.encode()
print(type(s))
- bytes 通过decode()方法转化为str
b = b'abc'
print(type(b))
# byte类型解码为str类型
s = b.decode()
priny(type(b)
注意编码和解码的方式必须一样,否则就会出现乱码!!!
3、字符、字符集
- 字符:是各种文字和符号的总称,包括各国文字、标点符号、图形符号、数字等
- 字符集:是多个字符的集合。包括ASCII字符集、GB2312字符集、GB18030字符集、Unicode字符集等。ASCII编码是1个字节,而Unicode编码是2个字节。
- UTF-8是Unicode的实现方式之一,utf-8是它是一种变长的编码方式,可以是1、2、3个字节。
4、Response的其他属性
- response.status_code 响应状态码
- response.request.headers 响应对应的请求头
- response.headers 响应头
- response.request.cookies 响应对应请求的cookie
- response.cookie 响应的cookie(经过了set-cookie动作)
5、发送请求时候的请求头
如果没有请求头,使用代码发送的请求会被服务器检测出来是爬虫代码,从而导致返回的结果不是所需要的内容或者内容不全,这种解决方案就是发送请求时带上header参数,模拟浏览器,欺骗服务器,从而获取和浏览器一模一样的内容。
- header的格式:
# 字典格式
header = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
}
6、实战案例:下载百度的图片、获取网页、获取网易云音乐
# 需求:把百度上的图片保存到本地
# 思考:1、以什么样的方式打开文件? 2、保存什么格式的内容?
# 分析:1、图片的url 2、利用request模块发送请求获取相应。 3、以二进制写入的方式打开文件,并将response响应的二进制内容写入。
import requests
url = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'
response = requests.get(url)
with open('baidu.png','wb') as f:
f.write(response.content)
以上面的代码为例子,也可以爬取网页的内容
import requests
url = 'https://www.baidu.com/'
header = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
}
response = requests.get(url, headers=header)
with open('baidu.html','w', encoding='utf-8') as f:
f.write(response.content.decode())
获取网易云歌曲
import requests
url = 'https://m704.music.126.net/20241209214722/eeb27e71d26abf5746732abe9e6f3421/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/28482111501/d0a2/d484/868a/2d1db9a86703105f5289140ef12a87c1.m4a?authSecret=00000193ab95d0b30aa00a3b195da0c5'
header = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
}
response = requests.get(url, headers=header)
with open('今天你要嫁给我.m4a','wb') as f:
f.write(response.content)
更多推荐




所有评论(0)