Requests 快速上手
导入包
import requests
requests实例获取信息
r = requests.post(url='http://httpbin.org/get')
print(r.text)#获取文本
print(r.status_code)#获取状态码
print(r.cookies)#获取cookie
print(r.headers)#获取headers
#获取headers其中某个值的属性如
r.headers['Content-Type']
r.headers.get('content-type')
r.raise_for_status()#抛出异常
发送请求
import requests
#下面有各种请求
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')
r = requests.get(url='http://httpbin.org/get')
r = requests.post(url='http://httpbin.org/get')
print(r.text)#获取文本
print(r.status_code)#获取状态码
修改请求头
import requests
get_headers = {
'Content-Length': '34',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
'Connection': 'close'
}
r = requests.get(url='http://httpbin.org/get',headers=get_headers)
print(r.text)
设置代理
import requests
proxies = {
"http": "http://127.0.0.1:8848"
}
r = requests.get("http://httpbin.org/get",proxies=proxies)
print(r.url)
print(r.text)
POST传递Data
import requests
playload = 'target=192.168.1.1+%26%26+'
r = requests.post(url='http://httpbin.org/get',data=playload)
print(r.cookies)
print(r.text)#获取文本
print(r.status_code)#获取状态码
POST一个文件
Requests 使得上传多部分编码文件变得很简单:
import requests
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text
Get传递 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
响应状态码
我们可以检测响应状态码:
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
为方便引用,Requests还附带了一个内置的状态码查询对象:
>>> r.status_code == requests.codes.ok
True
如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status()
来抛出异常:
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404
>>> bad_r.raise_for_status()
Traceback (most recent call last):
File "requests/models.py", line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error
但是,由于我们的例子中 r
的 status_code
是 200
,当我们调用 raise_for_status()
时,得到的是:
>>> r.raise_for_status()
None
一切都挺和谐哈。
响应头
我们可以查看以一个 Python 字典形式展示的服务器响应头:
>>> r.headers
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
但是这个字典比较特殊:它是仅为 HTTP 头部而生的。根据 RFC 2616, HTTP 头部是大小写不敏感的。
因此,我们可以使用任意大写形式来访问这些响应头字段:
>>> r.headers['Content-Type']
'application/json'
>>> r.headers.get('content-type')
'application/json'
它还有一个特殊点,那就是服务器可以多次接受同一 header,每次都使用不同的值。但 Requests 会将它们合并,这样它们就可以用一个映射来表示出来,参见 RFC 7230:
A recipient MAY combine multiple header fields with the same field name into one "field-name: field-value" pair, without changing the semantics of the message, by appending each subsequent field value to the combined field value in order, separated by a comma.
接收者可以合并多个相同名称的 header 栏位,把它们合为一个 "field-name: field-value" 配对,将每个后续的栏位值依次追加到合并的栏位值中,用逗号隔开即可,这样做不会改变信息的语义。
Cookie
如果某个响应中包含一些 cookie,你可以快速访问它们:
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'
要想发送你的cookies到服务器,可以使用 cookies
参数:
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
Cookie 的返回对象为 RequestsCookieJar
,它的行为和字典类似,但接口更为完整,适合跨域名跨路径使用。你还可以把 Cookie Jar 传到 Requests 中:
>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
>>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
>>> url = 'http://httpbin.org/cookies'
>>> r = requests.get(url, cookies=jar)
>>> r.text
'{"cookies": {"tasty_cookie": "yum"}}'
超时
你可以告诉 requests 在经过以 timeout
参数设定的秒数时间之后停止等待响应。基本上所有的生产代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应:
>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
注意
timeout
仅对连接过程有效,与响应体的下载无关。 timeout
并不是整个下载响应的时间限制,而是如果服务器在 timeout
秒内没有应答,将会引发一个异常(更精确地说,是在 timeout
秒内没有从基础套接字上接收到任何字节的数据时)If no timeout is specified explicitly, requests do not time out.
错误与异常
遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError
异常。
如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status()
会抛出一个 HTTPError
异常。
若请求超时,则抛出一个 Timeout
异常。
若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects
异常。
所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException
。
例子
import requests
get_headers = {
'Content-Length': '34',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
'Connection': 'close'
}
playload = 'target=192.168.1.1+%26%26+'
r = requests.get(url='http://httpbin.org/get',data=playload,headers=get_headers)
print(r.cookies)
print(r.text)#获取文本
print(r.status_code)#获取状态码
#传cookies例子
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies,proxies=proxies)
print(r.cookies)
print(r.text)
#上传文件例子
url = 'http://httpbin.org/post'
files = {'file': open('test.txt', 'rb')}
r = requests.post(url, files=files,proxies=proxies)
print(r.text)