Python3 Requests模块

发送请求
使用 Requests 发送网络请求非常简单。

一开始要导入 Requests 模块:

import requests
然后,尝试获取某个网页。本例子中,我们来获取 Github 的公共时间线:

r = requests.get(‘https://api.github.com/events‘)
现在,我们有一个名为 r 的 Response 对象。我们可以从这个对象中获取所有我们想要的信息。

Requests 简便的 API 意味着所有 HTTP 请求类型都是显而易见的。例如,你可以这样发送一个 HTTP POST 请求:

r = requests.post(‘http://httpbin.org/post‘, data = {‘key’:’value’})
漂亮,对吧?那么其他 HTTP 请求类型:PUT,DELETE,HEAD 以及 OPTIONS 又是如何的呢?都是一样的简单:

r = requests.put(‘http://httpbin.org/put‘, data = {‘key’:’value’})
r = requests.delete(‘http://httpbin.org/delete‘)
r = requests.head(‘http://httpbin.org/get‘)
r = requests.options(‘http://httpbin.org/get‘)
都很不错吧,但这也仅是 Requests 的冰山一角呢。

传递 URL 参数
你也许经常想为 URL 的查询字符串(query string)传递某种数据。如果你是手工构建 URL,那么数据会以键/值对的形式置于 URL 中,跟在一个问号的后面。例如, httpbin.org/get?key=val。 Requests 允许你使用 params 关键字参数,以一个字符串字典来提供这些参数。举例来说,如果你想传递 key1=value1 和 key2=value2 到 httpbin.org/get ,那么你可以使用如下代码:

payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
r = requests.get(“http://httpbin.org/get“, params=payload)
通过打印输出该 URL,你能看到 URL 已被正确编码:

print(r.url)
http://httpbin.org/get?key2=value2&key1=value1
注意字典里值为 None 的键都不会被添加到 URL 的查询字符串里。

你还可以将一个列表作为值传入:

payload = {‘key1’: ‘value1’, ‘key2’: [‘value2’, ‘value3’]}

r = requests.get(‘http://httpbin.org/get‘, params=payload)
print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
响应内容
我们能读取服务器响应的内容。再次以 GitHub 时间线为例:

import requests
r = requests.get(‘https://api.github.com/events‘)
r.text
u’[{“repository”:{“open_issues”:0,”url”:”https://github.com/
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。

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

r.encoding
‘utf-8’
r.encoding = ‘ISO-8859-1’
如果你改变了编码,每当你访问 r.text ,Request 都将会使用 r.encoding 的新值。你可能希望在使用特殊逻辑计算出文本的编码的情况下来修改编码。比如 HTTP 和 XML 自身可以指定编码。这样的话,你应该使用 r.content 来找到编码,然后设置 r.encoding 为相应的编码。这样就能使用正确的编码解析 r.text 了。

在你需要的情况下,Requests 也可以使用定制的编码。如果你创建了自己的编码,并使用 codecs 模块进行注册,你就可以轻松地使用这个解码器名称作为 r.encoding 的值, 然后由 Requests 来为你处理编码。

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

r.content
b’[{“repository”:{“open_issues”:0,”url”:”https://github.com/
Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。

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

from PIL import Image
from io import BytesIO

i = Image.open(BytesIO(r.content))
JSON 响应内容
Requests 中也有一个内置的 JSON 解码器,助你处理 JSON 数据:

import requests

r = requests.get(‘https://api.github.com/events‘)
r.json()
[{u’repository’: {u’open_issues’: 0, u’url’: ‘https://github.com/
如果 JSON 解码失败, r.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问 r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。

需要注意的是,成功调用 r.json() 并意味着响应的成功。有的服务器会在失败的响应中包含一个 JSON 对象(比如 HTTP 500 的错误细节)。这种 JSON 会被解码返回。要检查请求是否成功,请使用 r.raise_for_status() 或者检查 r.status_code 是否和你的期望相同。

原始响应内容
在罕见的情况下,你可能想获取来自服务器的原始套接字响应,那么你可以访问 r.raw。 如果你确实想这么干,那请你确保在初始请求中设置了 stream=True。具体你可以这么做:

r = requests.get(‘https://api.github.com/events‘, stream=True)
r.raw

导入 Request模块

#######################Get请求#######################

# 发送无参数的get请求
baiDu_response = requests.get('http://www.baidu.com')

# 发送无参数的get请求 设置超时时间 timeout 单位秒
baiDu_response = requests.get('http://www.baidu.com', timeout=1)

# 查看发送请求的url地址
print('无参数的get请求地址为: ' + baiDu_response.url)

# 查看当前返回状态码
# 若状态码为200 等同于 baiDu_response.status_code == requests.codes.ok 返回为True
print('返回的状态码为: '+str(baiDu_response.status_code))

# 查看当前返回内容编码
print('返回内容编码格式为:' + baiDu_response.encoding)

# 查看当前返回内容    text返回的是字符串
print('Text返回的数据内容为:' + baiDu_response.text)

# 查看当前返回内容    content返回的是字节流
# print('Content返回的数据内容为:' + baiDu_response.content)

# 若返回内容为json格式 可用如下语句
# print('返回的Json数据为:' + baiDu_response.json())

# 获取服务器返回的原始数据 增加stream=True
# data = requests.get('https://api.github.com/events', stream=True)
# print(data.raw.read())

# 发送带参数(字典形式)的get请求
sendDictParams = {'key1': 'value1', 'key2': 'value2'}
baiDu_dictParams_response = requests.get('http://www.baidu.com', params=sendDictParams)

# 查看发送请求的url地址
print('普通参数的get请求地址为: ' + baiDu_dictParams_response.url)

# 发送list格式参数的get请求
sendListParams = {'key1': 'value1', 'key2': ['value2', 'value3']}
baiDu_listParams_response = requests.get('http://www.baidu.com', params=sendListParams)

# 查看发送请求的url地址
print('带list参数的get请求地址为: ' + baiDu_listParams_response.url)

#######################Post请求#######################

# tips:强烈建议使用二进制模式打开文件,因为如果以文本文件格式打开时,可能会因为“Content-Length”这个header而出错
# post 请求参数是通过data方式来传递的

# 第一种方式:字典格式
postResponse = requests.post("http://pythontab.com/postTest", data={'key': 'value'})
print('普通参数请求返回状态码为:' + str(postResponse.status_code))

# 第二种方式 json格式 注意json方法为dumps() 不是dump()
jsonParams = {'key': 'value'}
postJsonResponse = requests.post("http://pythontab.com/postTest", data=json.dumps(jsonParams))
print('json参数请求返回状态码为:' + str(postJsonResponse.status_code))

# 第三种方式 发送文件  (该文件同级目录下需要有test.csv文件 )rb 只读模式  wb 若没有 自动创建
files = {'file': open('test.csv', 'rb')}
fileResponse = requests.post('http://pythontab.com/postTest', files=files)
print('文件参数请求返回状态码为:' + str(fileResponse.status_code))


#######################Headers#######################
headers_response = requests.get('http://www.baidu.com')

# 查看请求响应头 :字典格式 输入时转换为字符打印到控制台
print('请求响应头为: ' + str(headers_response.headers))

# 获取请求响应头其中某一个参数
print('请求响应头的Server参数   写法一:' + headers_response.headers['Server'])

# 等同于
print('请求响应头的Server参数   写法二:' + headers_response.headers.get('Server'))

# 自定义headers 并发送
headers = {'user-agent': 'myAgent'}
custom_headers_response = requests.get('http://www.baidu.com', headers=headers)
print('自定义header发送请求状态码为:' + str(custom_headers_response.status_code))


#######################Cookies#######################
cookies_response = requests.get('http://www.baidu.com')

# 查看请求响应头 :字典格式 输入时转换为字符
print('请求地址的Cookies为: ' + str(cookies_response.cookies))

# 自定义Cookies 并发送
cookies = {'user-cookies': 'myCookies'}
custom_cookies_response = requests.get('http://www.baidu.com', cookies=cookies)
print('自定义Cookies发送请求状态码为:' + str(custom_cookies_response.status_code))

#######################代理#######################

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}
# 通过代理方式发起请求 此处运行不通过,仅举例使用
# requests.get("http://baidu.com", proxies=proxies)


#######################Session#######################
# 通过requests获取session
session = requests.Session()
# 举例:登录名 密码  key为登陆表单中对应的input的name值
login_data = {'email': '[email protected]', 'password': 'password'}
# 发送数据
session.post("http://pythontab.com/testLogin", login_data)
# 获取发送的session
session_response = session.get('http://pythontab.com/notification/')
print('session请求返回的状态码为:' + str(session_response.status_code))

#######################下载页面#######################

baiDuHtmlContent = requests.get("http://www.baidu.com")
with open("百度.html", "wb") as html:
    html.write(baiDuHtmlContent.content)
html.close()

猜你喜欢

转载自blog.csdn.net/xiaozhiit/article/details/82668410