美文网首页
requests库

requests库

作者: 冷小谦 | 来源:发表于2018-09-29 10:55 被阅读9次

导入模块

使用requests库之前需要先导入模块。

import requests

发送请求

requests模块发出get请求,即可获取整个网页的信息,也可以加入params来传递参数,params是个字典,加入headers

r = requests.get('http://httpbin.org')
r = requests.get('http://httpbin.org',params = data)
headers= {'user-agent':'my-app/0.0.1'}
r = requests.get(url,headers=headers)
r.url来获取url

或者也可以使用post请求

r = requests.post('http://httpbin.org/post', data = {'key':'value'})

响应内容

requests可以自动解码服务器的内容,基于http头部信息对响应进行编码,也可以用r.encoding来自定义编码。

r.text文本
r.content二进制文件(图片)
r.json()处理json数据
r.status_code响应码
r.headers响应头,字典形式

cookie

响应中访问字典

 url = 'http://example.com/some/cookie/setting/url'
 r = requests.get(url)
 r.cookies['example_cookie_name']

请求cookie

url = 'http://httpbin.org/cookies'
 cookies = dict(cookies_are='working')
 r = requests.get(url, cookies=cookies)
 r.text

cookie返回对象是RequstsCookieJar,可以将此对象传入Requests中进行请求

jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie','yum',domain='httpbin.org', path='/cookies')
url = requests.get(url,cookies=jar)
r.text

会话对象

会话对象让你能够跨请求保持参数,在同一个Session实例发出所有请求之间保持cookie。
跨请求保持cookie,如果不用session无法保持统一状态请求

s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r= s.get("http://httpbin.org/cookies")
r.text

SSL证书

request能为https请求验证证书,就像web浏览器一样

requests.get('https://github.com', verify=False)主机证书
requests.get('https://github.com', verify='/path/to/certfile')可信任的CA证书路径

代理设置

如果需要使用代理,你可以通过为任意请求方法提供 proxies 参数来配置单个请求

import requests
http:
proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}
socks:
proxies = {
    'http': 'socks5://user:pass@host:port',
    'https': 'socks5://user:pass@host:port'
}
requests.get("http://example.org", proxies=proxies)

相关文章

网友评论

      本文标题:requests库

      本文链接:https://www.haomeiwen.com/subject/ifdvoftx.html