前言

参考链接:

1 2 3

request是python爬虫的一个基本的库,功能十分齐全。
下面对一些常用的方法进行说明:
(response——指接受返回的响应)

url:发送请求到链接.
params:携带的参数.
headers:头部信息.
Data:携带的json参数
cookie:用于网页认证,不要填错,单独添加.

  1. requests.get(url, params,headers)

  2. requests.post(url,data,headers)

  3. requests.raise_for_satus
    如果状态码不是200,这个方法可以抛出异常

  4. response.encoding
    返回信息的编码格式

  5. response.apparent_encoding
    解析返回数据是什么编码格式,一般使用方式
    respons.encoding = response.apparent_encoding
    通常用在爬取中文的网页,防止乱码

  6. respnse.json()

    获取返回回来的json数据

  7. response.text
    获取返回回来的html文本信息

  8. response.conent
    Html响应的二进制信息

常用方法

所有示例都是以Github官网为例

发送请求

发起GET请求;

1
r = requests.get('https://github.com/')

发起POST请求;

1
r = requests.post('https://github.com/',data = {'key':'value'})

其他 HTTP 请求类型:PUT,DELETE,HEAD 以及 OPTIONS

1
2
3
4
r = requests.put('https://github.com/', data = {'key':'value'}) 
r = requests.delete('https://github.com/delete')
r = requests.head('https://github.com//get')
r = requests.options('https://github.com/get')

查看请求头

查看GET请求的响应头为例,POST请求同理:

1
r.request.headers

查看请求头的某一属性:(大小写不影响)

1
2
r.request.headers['Accept-Encoding']
r.request.headers.get('user-agent')

查看响应内容

查看服务器返回页面的内容,以查看GET请求的响应内容为例,POST请求同理:

1
2
r = requests.get('https://github.com/')
r.text

Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。

请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用r.encoding 属性来改变它:

1
2
3
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

二进制响应内容

你也能以字节的方式访问请求响应体,对于非文本请求:

1
>>> r.content

Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。

例如,以请求返回的二进制数据创建一张图片,你可以使用如下代码:

1
2
3
>>> from PIL import Image
>>> from io import BytesIO
>>> i = Image.open(BytesIO(r.content))

传递GET请求参数

GET请求参数作为查询字符串附加在URL末尾,可以通过requests.get()方法中的params参数(dict类型变量)完成。例如,我要构建的URL为https://github.com/?username=jwt&id=1,则可以通过以下代码传递GET请求参数:

1
2
3
4
>>> args = {'username': 'jwt', 'id': 1}
>>> r = requests.get('https://github.com/', params = args)
>>> print(r.url)
https://github.com/?username=jwt&id=1