这里有一个新的学习requests网站:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
2017/11/30

Requests is the only Non-GMO HTTP library for Python, safe for human consumption.

Note

The use of Python 3 is highly preferred over Python 2. Consider upgrading your applications and infrastructure if you find yourself still using Python 2 in production today. If you are using Python 3, congratulations — you are indeed a person of excellent taste. ———

>>> import requests

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

Now, we have a response object called r. We can get all the information we need from this object.

For example, this is how you make an HTTP POST request:

>>> r = requests.post('http://xxxxx.com/post', data = {'key':'value'})

What about the other HTTP request types: PUT, DELETE, HEAD and OPTIONS? These are all just as simple:

>>> r = requests.put('http://xxxxxx.org/put', data = {'key':'value'})
>>> r = requests.delete('http://xxxxxxxx.org/delete')
>>> r = requests.head('http://xxxxxxx.org/get')
>>> r = requests.options('http://xxxxxxxxxx.org/get')
  • Passing Parameters In URLs

We often want to send some sort of data in the URL's query string.

As an example, if you wanted to pass key1=value1 and key2=value2 to httpbin.org/get, you would use the following code:

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('http://xxxxx.org/get', params=payload)

You can see that the URL has been correctly encoded;

>>> print(r.url)
http://httpbin.org/get?key2=value2&key1=value1

You can also pass a list of items as a value:

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

>>> r = requests.get('http://xxxx.org/get', params=payload)
>>> print(r.url)
http://xxxx.org/get?key1=value1&key2=value2&key2=value3
  • Response Content

>>> import requests

>>> r = requests.get("http://www.baidu.com")
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge>

When you make a request, Requests makes educated guesses about the encoding of the response based on the HTTP headers. The text encoding guessed by Requests is used when you access r.text. You can find out what encoding Requests is using, and change it, using the r.encoding property:

>>> r.encoding
'ISO-8859-1'
>>> r.encoding = 'utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=alway

If you change the encoding, Requests will use the new value of r.encoding whenever you call r.text.

If you have created your own encoding and registered it with the codecs module, you can simply use the codec name as the value of r.encoding and Requests will handle the decoding for you.

  • Binary Response Content

>>> r.content
b'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always

You can also access the response body as bytes, for non-text requests.

The gzip and deflate transfer-encodings are automatically decoded for you.

For example, to create an image from binary data returned by a request, you can use the following code:

>>> from PIL import Image
>>> from io import BytesIO >>> i = Image.open(BytesIO(r.content))
  • JSON Response Content

>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{'id': '6736180556', 'type': 'PushEvent', 'actor': {'id': 14111893, 'login': 'rvitorgomes', 'display_login': 'rvitorgomes', 'gravatar_id': '', 'url': 'https://api.github.com/users/rvitorgomes', 'avatar_url': 'https://avatars.g

In case the JSON decoding fails, r.json() raises an exception. For example, if the response gets a 204 (No Content), or if the response contains invalid JSON, attempting r.json() raises ValueError: No JSON object could be decoded.

It should be noted that the success of the call to r.json() does not indicate the success of the response. Some servers may return a JSON object in a failed response (e.g. error details with HTTP 500). Such JSON will be decoded and returned. To check that a request is successful, use r.raise_for_status() or check r.status_code is what you expect.

  • Raw Response Content

In the rare case that you'd like to get the raw socket response from the server, you can access r.raw. If you want to do this, make sure you set stream=True in your initial request. Once you do, you can do this:

>>> r = requests.get('https://api.github.com/events', stream=True)

>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810> >>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
  • Custom Headers

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'} >>> r = requests.get(url, headers=headers)

Note: Custom headers are given less precedence than more specific sources of information. For instance:

  1. Authorization headers set with headers= will be overridden if credentials are specified in .netrc, which in turn will be overridden by the auth= parameter.
  2. Authorization headers will be removed if you get redirected off-host.
  3. Proxy-Authorization headers will be overridden by proxy credentials provided in the URL.
  4. Content-Length headers will be overridden when we can determine the length of the content.

Furthermore, Requests does not change its behavior at all based on which custom headers are specified. The headers are simply passed on into the final request.

Note: All header values must be a string, bytestring, or unicode. While permitted, it's advised to avoid passing unicode header values.

  • More complicated POST requests

Typically, you want to send some form-encoded data — much like an HTML form. To do this, simply pass a dictionary to the data argument. Your dictionary of data will automatically be form-encoded when the request is made:

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

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}

You can also pass a list of tuples to the data argument. This is particularly useful when the form has multiple elements that use the same key:

>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key1": [
"value1",
"value2"
]
},
...
}

There are times that you may want to send data that is not form-encoded. If you pass in a string instead of a dict, that data will be posted directly.

For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data:

>>> import json
>>>import requests >>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'} >>> r = requests.post(url, data=json.dumps(payload))

Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'} >>> r = requests.post(url, json=payload)
>>> print(r.text)
{
  "args": {},
  "data": "{\"key1\": \"value1\", \"key2\": \"value2\"}",
  "files": {},
  "form": {},
  • POST a Multipart-Encoded File(多重编码文件)

Requests makes it simple to upload Multipart-encoded files:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')} >>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}

You can set the filename, content_type and headers explicitly:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})} >>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
  • Response Status Codes

*详见之前博客,http响应码

>>> r = requests.get('http://www.baidu.com')
>>> r.status_code
200

Requests also comes with a built-in status code lookup object for easy reference:

>>> r.status_code == requests.codes.ok
True

If we made a bad request (a 4XX client error or 5XX server error response), we can raise it with 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

But, since our status_code for r was 200, when we call raise_for_status() we get:

>>> r.raise_for_status()
None
  • Response Headers

We can view the server's response headers using a Python dictionary:

>>> r.headers
{'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Thu, 19 Oct 2017 02:34:53 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000764846801758', 'Content-Length': '488', 'Via': '1.1 vegur'}

or,we can access the headers using any capitalization we want:

>>> r.headers["Date"]
'Thu, 19 Oct 2017 02:34:53 GMT'
>>> r.headers["Connection"]
'keep-alive'
  • Cookies

If a response contains some Cookies, you can quickly access them:

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url) >>> r.cookies['example_cookie_name']
'example_cookie_value' 我这里执行失败的,先记录下来吧

To send your own cookies to the server, you can use the cookies parameter:

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are = 'working')
>>> r = requests.get(url,cookies = cookies)
>>> r.text
'{\n "cookies": {\n "cookies_are": "working"\n }\n}\n'

Cookies are returned in a RequestsCookieJar, which acts like a dict but also offers a more complete interface, suitable for use over multiple domains or paths. Cookie jars can also be passed in to requests:

>>> jar = requests.cookies.RequestsCookieJar()
>>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
Cookie(version=0, name='tasty_cookie', value='yum', port=None, port_specified=False, domain='httpbin.org', domain_specified=True, domain_initial_dot=False, path='/cookies', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
>>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
Cookie(version=0, name='gross_cookie', value='blech', port=None, port_specified=False, domain='httpbin.org', domain_specified=True, domain_initial_dot=False, path='/elsewhere', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
>>> url = 'http://httpbin.org/cookies'
>>> r = requests.get(url, cookies=jar)
>>> r.text
'{\n "cookies": {\n "tasty_cookie": "yum"\n }\n}\n'
  • Timeouts

>>> requests.get("http://www.baidu.com",timeout = 0.001)
Traceback (most recent call last):
File "C:\Users\yangbo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connection.py", line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "C:\Users\yangbo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\util\connection.py", line 83, in create_connection
raise err
File "C:\Users\yangbo\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\util\connection.py", line 73, in create_connection
sock.connect(sa)
socket.timeout: timed out

python基础===requests学习笔记的更多相关文章

  1. Python基础教程学习笔记:第一章 基础知识

    Python基础教程 第二版 学习笔记 1.python的每一个语句的后面可以添加分号也可以不添加分号:在一行有多条语句的时候,必须使用分号加以区分 2.查看Python版本号,在Dos窗口中输入“p ...

  2. Python基础班学习笔记

    本博客采用思维导图式笔记,所有思维导图均为本人亲手所画.因为本人也是初次学习Python语言所以有些知识点可能不太全. 基础班第一天学习笔记:链接 基础班第二天学习笔记:链接 基础班第三天学习笔记:链 ...

  3. 【学习笔记】Python基础教程学习笔记

    教程视频网盘共享:http://pan.baidu.com/s/1hrTrR5E 03-python基础.if判断 print 输出数据 print("hahahah")----- ...

  4. Python 基础语法学习笔记

    以下运行结果均通过Python3.5版本实测! 1.列表转换为字典 a = ['a', 'b'] b = [1, 2] c = ['c','d'] print (dict([a,b,c])) 输出结果 ...

  5. Python基础教程学习笔记:第二章 列表和元组

    1.序列中元素的索引: 第一个元素索引是0,第二个是1,依次递增 最后一个元素索引是-1,倒数第二个是-2,依次递减 2.序列(Sequence)的种类: 列表(list).元组(tuple).字符串 ...

  6. Requests:Python HTTP Module学习笔记(一)(转)

    Requests:Python HTTP Module学习笔记(一) 在学习用python写爬虫的时候用到了Requests这个Http网络库,这个库简单好用并且功能强大,完全可以代替python的标 ...

  7. Python基础知识总结笔记(四)函数

    Python基础知识总结笔记(四)函数python中的函数函数中的参数变量作用域偏函数PFA递归函数高阶函数BIFs中的高阶函数匿名函数lambda闭包Closure装饰器Decorator函数式编程 ...

  8. python网络爬虫学习笔记

    python网络爬虫学习笔记 By 钟桓 9月 4 2014 更新日期:9月 4 2014 文章文件夹 1. 介绍: 2. 从简单语句中開始: 3. 传送数据给server 4. HTTP头-描写叙述 ...

  9. linux基础命令学习笔记(二)

    linux基础命令学习笔记(二) 1.kill :终止进程  kill pid (唯一标示一个进程) kill -9  强制终止  kill -15 命令未结束不能终止 # ps aux 查看所有进程 ...

随机推荐

  1. asp.net中缓存的使用

    刚学到asp.net怎么缓存,这里推荐学习一下 www.cnblogs.com/wang726zq/archive/2012/09/06/cache.html http://blog.csdn.net ...

  2. SpringBoot使用servletAPI与异常处理

    工程结构: 主方法类: package com.boot.servlet.api.bootservlet; import org.springframework.boot.SpringApplicat ...

  3. httpservlet在创建实例对象时候默认调用有参数的init方法 destroy()方法 service方法, 父类的init方法给子类实例一个config对象

  4. request 域 个人理解

    1.转发到另一个servlet时候 地址还是输入当前的servlet 2.通过服务器转到另一个servlet时候 另一个servlet是最终接收端 端到端模式 相当于这个东西是发给自己的 只不过经过多 ...

  5. BZOJ 1015 星球大战(并查集)

    正着不好搞,考虑倒着搞.倒着搞就是一个并查集. # include <cstdio> # include <cstring> # include <cstdlib> ...

  6. 【bzoj2100】[Usaco2010 Dec]Apple Delivery 最短路

    题目描述 Bessie has two crisp red apples to deliver to two of her friends in the herd. Of course, she tr ...

  7. 【题解】CF#833 B-The Bakery

    一个非常明显的 \(nk\) dp 状态 \(f[i][k]\) 表示以 \(i\) 为第 \(k\) 段的最后一个元素时所能获得的最大代价.转移的时候枚举上一段的最后一个元素 \(j\)更新状态即可 ...

  8. [洛谷P3833][SHOI2012]魔法树

    题目大意:给一棵树,路径加,子树求和 题解:树剖 卡点:无 C++ Code: #include <cstdio> #include <iostream> #define ma ...

  9. POJ3648:Wedding——题解(配2-SAT简易讲解)

    http://poj.org/problem?id=3648 (在家,而且因为2-SAT写的不明不白的,所以这篇详细写) 题目大意: 有一对新人结婚,邀请了n-1 对夫妇去参加婚礼.婚礼上所有人要坐在 ...

  10. 洛谷 P2446 [SDOI2010]大陆争霸 解题报告

    P2446 [SDOI2010]大陆争霸 题目背景 在一个遥远的世界里有两个国家:位于大陆西端的杰森国和位于大陆东端的克里斯国.两个国家的人民分别信仰两个对立的神:杰森国信仰象征黑暗和毁灭的神曾·布拉 ...