pip install requests
简单使用
import requests
r = requests.get('http://www.baidu.com')
print type(r)
print r.status_code
print r.encoding
print r.text
print r.cookies
'''请求了百度的网址,然后打印出了返回结果的类型,状态码,编码方式,Cookies等内容
输出:'''
<class 'requests.models.Response'>
200
UTF-8
<RequestsCookieJar[]>
http 请求
r = requests.post("http://httpbin.org/post")
r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")
get请求
r = requests.get("http://httpbin.org/get")
#如果想要加参数,可以利用 params 参数:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
print r.url
#输出:http://httpbin.org/get?key2=value2&key1=value1
添加 headers
mport requests
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'content-type': 'application/json'}
r = requests.get("http://httpbin.org/get", params=payload, headers=headers)
print r.url
#通过headers参数可以增加请求头中的headers信息
请求 json
import requests
r = requests.get("a.json")
print r.text
print r.json()
'''运行结果如下,其中一个是直接输出内容,另外一个方法是利用 json() 方法
解析,感受下它们的不同:'''
["foo", "bar", {
"foo": "bar"
}]
[u'foo', u'bar', {u'foo': u'bar'}]
post 请求
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print r.text
超时配置
requests.get(‘Build software better, together’, timeout=0.001
代理设置
设置代理有两种方法
import requests
proxies = {
"https": "http://41.118.132.69:4433"
}
r = requests.post("http://httpbin.org/post", proxies=proxies)
print r.text
#也可以通过环境变量 HTTP_PROXY 和 HTTPS_PROXY 来配置代理
export HTTP_PROXY="http://10.10.1.10:3128"
export HTTPS_PROXY="http://10.10.1.10:1080"
会话对象
import requests
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print(r.text)