Python学习笔记-Requests

1、安装

终端cmd 输入:

pip install requests

2、发送请求

import requests

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

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

3、传递参数

URL参数可直接跟在问号后,置于URL之后,如:httpbin.org/get?key=val,除此以外,

get方法:

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

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

post方法:

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

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

其中,若请求参数为json:先将参数转化为json格式(json.dumps())

>>>import  json

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

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

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

2.4.2版本之后可直接使用json参数传递

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

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

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

上传文件参数(Multipart-Encoded):

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

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

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

4、响应内容

>>>importrequests

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

>>>r.text

u'[{"repository":{"open_issues":0,"url":"https://github.com/...

Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。

请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问r.text之时,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))

Requests 中也有一个内置的 JSON 解码器,来处理 JSON 数据:

>>>import  requests

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

>>>r.json()

[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

>>>r.json()['url']           #获取json属性值

如果 JSON 解码失败,r.json()就会抛出一个异常。例如,相应内容是 401 (Unauthorized),尝试访问r.json()将会抛出ValueError:NoJSONobjectcouldbedecoded异常。

5、定制请求头

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

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

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

注意: 定制 header 的优先级低于某些特定的信息源,例如:

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

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

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

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

更进一步讲,Requests 不会基于定制 header 的具体情况改变自己的行为。只不过在最后的请求中,所有的 header 信息都会被传递进去。

注意: 所有的 header 值必须是string、bytestring 或者 unicode。尽管传递 unicode header 也是允许的,但不建议这样做。

6、响应状态码

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

>>>r.status_code

200

如果发送了一个错误请求(一个 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", line832, in raise_for_statusraisehttp_error

requests.exceptions.HTTPError:404 Client Error

7、响应头

>>>r.headers

{'content-encoding': 'gzip','transfer-encoding': 'chunked','connection': 'close','server': 'nginx/1.0.4','x-runtime': '148ms','etag': '"e1ca502697e5c9317743dc078f67693f"','content-type': 'application/json'}

8、Cookie

响应中包含cookie,可快速访问

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

>>>r=requests.get(url)

>>>r.cookies['example_cookie_name']

'example_cookie_value'

也使用cookie参数,发送cookie到服务器,

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

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

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

>>>r.text

'{"cookies": {"cookies_are": "working"}}'

9.其他

重定向和请求历史:

默认情况下,除了 HEAD, Requests 会自动处理所有重定向。

可以使用响应对象的history方法来追踪重定向。

Response.history是一个Response对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

例如,Github 将所有的 HTTP 请求重定向到 HTTPS:

>>>r=requests.get('http://github.com')

>>>r.url'https://github.com/'

>>>r.status_code200

>>>r.history

[< Response [301]>]

如果你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通过allow_redirects参数禁用重定向处理:

>>>r =requests.get('http://github.com', allow_redirects=False)

>>>r.status_code

301

超时

你可以告诉 requests 在经过以timeout参数设定的秒数时间之后停止等待响应:

>>>requests.get('http://github.com',timeout=0.001)

注意

timeout仅对连接过程有效,与响应体的下载无关。timeout并不是整个下载响应的时间限制,而是如果服务器在timeout秒内没有应答,将会引发一个异常(更精确地说,是在timeout秒内没有从基础套接字上接收到任何字节的数据时)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,881评论 18 139
  • 目录: Python网络爬虫(一)- 入门基础Python网络爬虫(二)- urllib爬虫案例Python网络爬...
    一只写程序的猿阅读 12,982评论 17 68
  • 1.发送请求: import requests # 获取数据 #r是一个 response 对象。包含请求返回的内...
    阿尔卑斯山上的小灰兔阅读 1,413评论 0 3
  • 深夜回到家,屋中一片漆黑,不是伸手不见五指,只是家具只有背影。 不想开灯,太累了,想躺一躺。 可躺在床上,时间过了...
    李一十八阅读 326评论 0 0
  • 二零一七年九月八日,傍晚五点二十七分 在资本家戴女士威逼利诱之下,劳工阿戴开始了苦逼的创作。 事情是怎样发生的...
    寄北北阅读 715评论 0 0