python request 之路

介绍

python request模块通过模拟用户访问web网站,通过post,get的方法实现网站互动

 安装

pip 安装

pip install requests  

或源码

git clone git://github.com/kennethreitz/request.git

用法

导入模块

>>>import requests 

get获取网页信息,保存名为r的Response

>>>r = request.get('https://github.com/timeline.json')

 

request 请求类型

>>>r = request.post('https://httpbin.org/post')

>>>r = request.put('http://httpbin.org/put')

>>>r = request.delete('http://httpbin.org/delete')

>>>r = request.head('http://httbin.org/head')

>>>r = request.options('http://httpbin.org/options')

 

request url传递参数

requsets 允许使用params关键字参数,并且以一个字典的形式来提供这些参数,如你想传递key1=value1和key2=value2 到httpbin.org/get,你可以使用以下代码:

>>> payload = {'key1':'value1','key2':'value2'}

>>> r = requests.get("http://httbin.org/head",params=payload)

>>>print(r.url)

注意:字典值为None的键都不会被添加到url的参数字符串里

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

>>>payload = {'key1','value1','key2':['value2','value3']}

>>>r = request.get('http://httpbin.org/get',params=payload)

>>>print(r.url)

 

request 响应内容

>>>import requests

>>>r.request.get('https://github.com/timeline.json')

>>>r.text  # 返回请求的内容

>>>r.encoding  # 返回编码、

>>>r.encoding='ISO-8859-1'  # 设置编码

设置了新的编码后,再次访问r.text,Request都将会使用r.encoding设置新的编码

用途:html 或者xm自身可以指定编码,使用r.content找到对应的编码,然后设置使r.encoding为相应的编码,这样就能使用正确的编码解析r.text了

 

二进制响应内容

>>>r.content

>>>from PIL import Image

>>>from io import BytesIO

>>i = Image.open(BytesIO(r.content))

用途:把请求的二进制数据创建一张图片,可以使用此段代码

 

JSON 响应内容

>>>import requests

>>>r = requests.get('https://github.com/timeline.json')

>>>r.json()

注意:成功调用json并不意味响应成功,因为有的服务器会在失败的响应中包含json对象,这种json会被解码返回,要检查请求是否成功,请使用r.raise_for_status 或者检查r.status_code是否和你期望的相同

 

原始响应内容

如果你想要获取来自服务器的原始套接字符响应,你可以使用r.raw,如果你想这么做,请确保在原始请求中设置了stream=True,具体代码如下:

>>>r = requests.get(https://github.com/timeline.json',stream=Ture)

>>>r.raw

>>>r.raw.read(10)

一般情况下,将以下面的模式将文本流保存到文件

with open(filename,'wb') as fd:

    for chunk in r.iter_content(chunk_size):

        fd.write(chunk)

 

定制请求头

如果你想为http添加头部,只要传递一个dict给headers参数就ok了

>>> url = 'https://github.com/some/endpoint'

>>>headers = {'user-agent':'my-app/0.0.1'}

>>>r = request.get(url,headers=headers)

 注意:定制header的优先级低于一些特定的信息源

如果在.netrc中设置了用户认证信息,使用headers=设置的授权就不会生效,而如果设置了auth=参数,.netrcd的设置就无效了

如果被重定向到别的主机,授权header就会被删除

代理授权header会被url中提供的代理身份覆盖掉

在我们能判断内容长度的情况下,header的Content-Length会被改写

 

更加复杂的POST请求

>>>payload = {'key1':'value1','key2':'value2'}

>>>r = requests.post("http://httpbin.org/post",data=payload)

>>>print(r.text)

你还可以为data参数传入一个元组列表,在表单中多个元素使用同一个key的时候,这个种方式尤其有效

>>> payload=(('key1':'value1'),('key1':'value2'))

>>>r = requests.post("http://httpbin.org/post",data=payload)

>>>print(r.text)

很多是时候你想发送的数据并非编码为表单形式的,如果你传递一个string而不是dict,那数据将会被直接发布出去

如:

>>>import requests

>>> url = 'https://api.github.com/some/endpoint'

>>>payload = {'some':'data'}

>>>r = requests.post(url,data=json.dumps(payload))

除此之外,还可以通过json参数直接传递

>>>import requests

>>> url = 'https://api.github.com/some/endpoint'

>>>payload = {'some':'data'}

>>>r = requests.post(url,json=payload)

 

POST 一个多部分编码的文件

>>> url = 'http://httpbin.org/post'

>>>files = {'file':open('report.xls','rb')}

>>>r = requests.post(url,files=files)

>>>r.text

 

响应状态码

>>>r = request.get('http://httpbin.org/get')

>>>r.status_code

>>>r.status_code = requests.code.ok    #附带了一个内置的状态码查询

如果发送了一个错误请求,可通过Response.raise_for_status()来抛出异常

>>>bad_r = requeest.get("http://httpbin.org/status/404")

>>>bad_r.status_code

>>>bad_r.raise_for_status()

 

响应头

>>>r.headers

>>>r.headers['Content-Type']

>>>r.headers.get('content-type')

 

Cookie 如果响应头中包含cookie,你可以快速访问

>>>url = 'http://example.com/some/cookie/setting/url'

>>>r = request.get(url)

>>>r.cookies['example_cookie_name']

发送cookices到服务器,可以使用cookies参数

>>>url = 'http://httpbin.org/cookies'

>>>cookies = dict(cookies_are='working')

>>>r = rquesets.get(url,cookies=cookies)

>>>r.text

cookie 的返回对象为RequestsCookieJar,行为和字典类似,适合夸域名夸路径使用

>>>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

转载于:https://www.cnblogs.com/zbrook/p/7976131.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值