requests库的使用
requests
库是一个HTTP请求库,可以方便爬取网站数据
安装
使用 pipenv安装
1 | pipenv install requests |
使用pip3安装
1 | python3 -m pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple |
说明
python是面向对象编程的语言,只有知道数据是什么对象,才能知道对象有什么属性和方法可以用
1 | import requests |
结果:
1 | <class 'requests.models.Response'> |
表明 res
是一个 Response
对象,属于 requests.models.Response
类
Response
对象常用的四个属性:
属性 | 作用 |
---|---|
response.status_code | 检查请求是否成功 |
response.content | 将response对象转换为二进制数据 |
response.text | 将response对象转换为字符串数据 |
response.encoding | 定义response对象的编码 |
response.status_code
常见状态响应码:
响应状态码 | 作用 | 举例 | 作用 |
---|---|---|---|
1xx | 请求收到 | 100 | 继续提出请求 |
2xx | 请求成功 | 200 | 成功 |
3xx | 重定向 | 305 | 应使用代理访问 |
4xx | 客户端错误 | 403 | 禁止访问 |
5xx | 服务端错误 | 503 | 服务不可用 |
response.content
:用于图片、音频、视频下载,以二进制形式返回response.text
:用于网页源代码、文本下载,以字符串形式返回response.encoding
:用于定义编码,常用 gbk
和 utf-8
下载图片并保存
1 | import requests |