一、网络请求(3)——requests库

requests库

虽然 Python 的标准库中,urllib 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 宣传的是 “HTTP for Humans”,说明使用更简洁方便。

安装和文档地址

利用pip可以非常方便的安装:

pip install requests

中文文档:http://docs.python-requests.org/zh_CN/latest/index.html   github地址:https://github.com/requests/requests

发送GET请求

1. 最简单的发送get请求就是通过 requests.get 来调用:

response = requests.get('http://www.baidu.com')

2. 添加 headers和查询参数: 如果想添加 headers,可以传入 headers 参数来增加请求头中的 headers信息。如果要将参数放在url 中传递,可以利用 params 参数。相关示例代码如下:

import requests

kw = {'wd':'中国'}

headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"}

# params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.get("http://www.baidu.com/s",params=kw,headers=headers)

# 查看响应内容,response.text 返回的是Unicode格式的数据
print(response.text)

#查看响应内容,response.content 返回的是字节流数据
print(response.content)

# 查看完整url地址
print(response.url)

# 查看响应头部字符编码
print(response.encoding)

# 查看响应码
print(response.status_code)

 

response.text和response.content的区别

 1. response.content:这个是直接从网络上面抓取的数据,没有经过任何解码。所以是一个bytes类型。其实在硬盘上和在网络上传输的客符串都是bytes类型。

2. response.text:这个是str的数据类型,是requests库将response.content进行解码的字符串。解码需要指定 一个编码方式,requests会根据自己的猜测来判断编码的方式,所以有时候可能会猜测错误,就会导致解码产生乱码。这时候就应试使用response.content.decode('utf-8')进行手动解码。

发送POST请求

1. 最基本的POST请求可以使用requests.post方法:

response = requests.post("http://www.baidu.com",data=data)

2. 传入data数据:

这时候就不要再使用urlencode进行编码了,直接传入一个字典进去就可以了。如果返回的是json数据,那么就可以调用response.json()来将json字符串转换为字典或者列表。比如请求拉勾网的数据的代码:

import requests

data = {
    'first': 'true',  # 是不是第一页,false表示不是,true 表示是
    'kd': 'Python',  # 搜索关键字
    'pn': 1  # 页码
}
headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Referer': 'https://www.lagou.com/jobs/list_Android?px=default&city=%E6%B7%B1%E5%9C%B3',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',
}
url = 'https://www.lagou.com/jobs/positionAjax.json?px=default&city=%E6%B7%B1%E5%9C%B3&needAddtionalResult=false'

response = requests.post(url=url, data=data, headers=headers)
print(type(response.json()))
# 如果是json数据,直接可以调用json方法
print(response.json())

使用代理

使用requests添加代理也非常简单,只要在请求的方法中(比如get或者post)传递proxies参数就可以了。示例代码如下:

import requests

url = 'http://httpbin.org/ip'
proxy = {
    'http':'123.59.232.123:80'
}

resp = requests.get(url,proxies=proxy)
print(resp.text)

 

Cookie

如果在一个响应中包含了cookie,那么可以利用cookies属性拿到这个返回的cookie值:

import requests

resp = requests.get('http://www.baidu.com')
print(resp.cookies)
print(resp.cookies.get_dict())

 

Session

之前使用urllib库,是可以使用opener发送多个请求,多个请求之间是可以共享 cookie 的。那么如果使用 requests,也要达到共享cookie的目的,那么可以使用 requests库给我们提供的session对象。注意,这里的session不是web开发中的那个session,这个地方只是一个会话的对象而已。还是以登录人人网为例,使用requests来实现。示例代码如下:

import requests

url = "http://www.renren.com/PLogin.do"
data = {"email":"renjy185911222@126.com",'password':'caonima001'}
headers={
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
}
session = requests.Session()
# 登录
session.post(url,data=data,headers=headers)

response = session.get('http://www.renren.com/880151247/profile')
with open('renren.html','w',encoding='utf-8') as fp:
    fp.write(response.text)

 

处理不信任的ssl证书

对于那些已经被信任的SSL整数的网站,比如http://www.baidu.com,那么使用requests直接就可以正常的返回响应。示例代码如下:

resp = requests.get('https://www.12306.cn/index/',verify=False)
print(resp.content.decode('utf-8'))

 

posted @ 2019-04-30 17:52  渣爷  阅读(216)  评论(0)    收藏  举报