python发送http请求之requests模块

python的requests模块比urllib、urllib2模块的接口更简洁。

以下转自:http://blog.csdn.net/iloveyin/article/details/21444613

迫不及待了吗?本页内容为如何入门Requests提供了很好的指引。其假设你已经安装了Requests。如果还没有, 去 安装 一节看看吧。

首先,确认一下:

让我们从一些简单的示例开始吧。

发送请求

使用Requests发送网络请求非常简单。

一开始要导入Requests模块:

>>> import requests

然后,尝试获取某个网页。本例子中,我们来获取Github的公共时间线

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

现在,我们有一个名为 r 的 Response 对象。可以从这个对象中获取所有我们想要的信息。

Requests简便的API意味着所有HTTP请求类型都是显而易见的。例如,你可以这样发送一个HTTP POST请求:

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

漂亮,对吧?那么其他HTTP请求类型:PUT, DELETE, HEAD以及OPTIONS又是如何的呢?都是一样的简单:

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

都很不错吧,但这也仅是Requests的冰山一角呢。

为URL传递参数

你也许经常想为URL的查询字符串(query string)传递某种数据。如果你是手工构建URL,那么数据会以键/值 对的形式置于URL中,跟在一个问号的后面。例如,httpbin.org/get?key=val 。 Requests允许你使用 params 关键字参数,以一个字典来提供这些参数。举例来说,如果你想传递 key1=value1 和 key2=value2 到 httpbin.org/get ,那么你可以使用如下代码:

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

通过打印输出该URL,你能看到URL已被正确编码:

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

响应内容

我们能读取服务器响应的内容。再次以Github时间线为例:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
'[{"repository":{"open_issues":0,"url":"https://github.com/...

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

请求发出后,Requests会基于HTTP头部对响应的编码作出有根据的推测。当你访问r.text 之时,Requests会使用其推测的文本编码。你可以找出Requests使用了什么编码,并且能够使用 r.encoding 属性来改变它:

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

如果你改变了编码,每当你访问 r.text ,Request都将会使用 r.encoding 的新值。

在你需要的情况下,Requests也可以使用定制的编码。如果你创建了自己的编码,并使用codecs 模块进行注册,你就可以轻松地使用这个解码器名称作为 r.encoding 的值, 然后由Requests来为你处理编码。

二进制响应内容

你也能以字节的方式访问请求响应体,对于非文本请求:

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

Requests会自动为你解码 gzip 和 deflate 传输编码的响应数据。

例如,以请求返回的二进制数据创建一张图片,你可以使用如下代码:

>>> from PIL import Image
>>> from StringIO import StringIO
>>> i = Image.open(StringIO(r.content))

JSON响应内容

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

如果JSON解码失败, r.json 就会抛出一个异常。

原始响应内容

在罕见的情况下你可能想获取来自服务器的原始套接字响应,那么你可以访问 r.raw 。 如果你确实想这么干,那请你确保在初始请求中设置了 stream=True 。具体的你可以这么做:

>>> r = requests.get('https://github.com/timeline.json', 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'

定制请求头

如果你想为请求添加HTTP头部,只要简单地传递一个 dict 给 headers 参数就可以了。

例如,在前一个示例中我们没有指定content-type:

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}

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

更加复杂的POST请求

通常,你想要发送一些编码为表单形式的数据—非常像一个HTML表单。 要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典 在发出请求时会自动编码为表单形式:

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

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

例如,Github API v3接受编码为JSON的POST/PATCH数据:

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

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

POST一个多部分编码(Multipart-Encoded)的文件

Requests使得上传多部分编码文件变得很简单:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

你可以显式地设置文件名:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'))}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

如果你想,你也可以发送作为文件来接收的字符串:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "some,data,to,send\\nanother,row,to,send\\n"
  },
  ...
}

响应状态码

我们可以检测响应状态码:

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

为方便引用,Requests还附带了一个内置的状态码查询对象:

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

如果发送了一个失败请求(非200响应),我们可以通过 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

但是,由于我们的例子中 r 的 status_code 是 200 ,当我们调用 raise_for_status() 时,得到的是:

>>> r.raise_for_status()
None

一切都挺和谐哈。

响应头

我们可以查看以一个Python字典形式展示的服务器响应头:

>>> r.headers
{
    'status': '200 OK',
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json; charset=utf-8'
}

但是这个字典比较特殊:它是仅为HTTP头部而生的。根据 RFC 2616 , HTTP头部是大小写不敏感的。

因此,我们可以使用任意大写形式来访问这些响应头字段:

>>> r.headers['Content-Type']
'application/json; charset=utf-8'

>>> r.headers.get('content-type')
'application/json; charset=utf-8'

如果某个响应头字段不存在,那么它的默认值为 None

>>> r.headers['X-Random']
None

Cookies

如果某个响应中包含一些Cookie,你可以快速访问它们:

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)

>>> r.cookies['example_cookie_name']
'example_cookie_value'

要想发送你的cookies到服务器,可以使用 cookies 参数:

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'

重定向与请求历史

使用GET或OPTIONS时,Requests会自动处理位置重定向。

Github将所有的HTTP请求重定向到HTTPS。可以使用响应对象的 history 方法来追踪重定向。 我们来看看Github做了什么:

>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]

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

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

>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]

如果你使用的是POST,PUT,PATCH,DELETE或HEAD,你也可以启用重定向:

>>> r = requests.post('http://github.com', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]

超时

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

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

注:

timeout 仅对连接过程有效,与响应体的下载无关。

错误与异常

遇到网络问题(如:DNS查询失败、拒绝连接等)时,Requests会抛出一个ConnectionError 异常。

遇到罕见的无效HTTP响应时,Requests则会抛出一个 HTTPError 异常。

若请求超时,则抛出一个 Timeout 异常。

若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。

 

以下转自:http://ju.outofmemory.cn/entry/31375

# 0. 认证、状态码、header、编码、json
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
# 1. 发起请求
import requests
URL="http://www.bsdmap.com/"
r = requests.get(URL)
r = requests.post(URL)
r = requests.put(URL)
r = requests.delete(URL)
r = requests.head(URL)
r = requests.options(URL)
# 2. 通过URL传递参数
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
>>> print r.url
u'http://httpbin.org/get?key2=value2&key1=value1'
# 3. 返回内容
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
'[{"repository":{"open_issues":0,"url":"https://github.com/...
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
# 4. 二进制内容
You can also access the response body as bytes, for non-text requests:
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
The gzip and deflate transfer-encodings are automatically decoded for you.
For example, to create an image from binary data returned by a request,
 ou can use the following code:
>>> from PIL import Image
>>> from StringIO import StringIO
>>> i = Image.open(StringIO(r.content))
# 5. JSON
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
# 6. 超时
>>> requests.get('http://github.com', timeout=0.001)
# 7. 自定义header
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)

以下转自:http://blog.csdn.net/powerccna/article/details/38141959

request还提供了keep alive, SSL, 多文件上传,cookie 管理功能,http requests头管理等丰富的功能,只要你浏览器实现的功能,requests里面都支持。

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #!/usr/bin/env python  
  2. #coding=utf-8  
  3.   
  4. import requests  
  5.   
  6. def login_douban(username, passwd):  
  7.     post_data={'source':'index_nav','form_email':username,'form_password':passwd}  
  8.     request_headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0"}  
  9.     response=requests.post("http://www.douban.com/accounts/login", data=post_data,headers=request_headers)  
  10.     if u"小王子" in response.text:  
  11.         print "Login successful"  
  12.         return  response  
  13.     else:  
  14.         print "Login failed"  
  15.         print response.text  
  16.         return  False  
  17.   
  18. def say_something(login_cookie):  
  19.     post_data={'ck':'ynNl','rev_title':u'发福利','rev_text':u'楼主是标题党','rev_submit':u'好了,发言'}  
  20.     response=requests.post("http://www.douban.com/group/beijing/new_topic", data=post_data,cookies=login_cookie)  
  21.     if response.url=="http://www.douban.com/group/beijing/":  
  22.         print "post new content successfully"  
  23.         return  True  
  24.     else:  
  25.         print "Post content fail"  
  26.         return  False  
  27.   
  28. login_response=login_douban(your_usename,your_passwd)  
  29. say_something(login_response.cookies)  

request_headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0"}, 这一行的目的是为了模拟这个请求是FireFox发出来的,很多网站为了屏蔽爬虫,会通过User-Agent这个字段来屏蔽,当然现在大型网站应该会用更高级的手段来屏蔽爬虫,如果不设置这个User-Agent, requests发出去的请求,User-Agent的值是python-requests/2.3.0 CPython/2.7.3 Windows/7\r\n。


say_something这个函数没测试了,刚才我频繁的调试,豆瓣要我输入登陆验证码了,有问题这里留言,我过段时间在调试。


关于cookie, session管理这块,如果是在同一个函数里面,request自动管理了session,不需要额外的处理,

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. session = requests.Session()  
  2. session.post("http://www.douban.com/accounts/login", data=post_data,headers=request_headers)  
  3. session.post("http://www.douban.com/group/beijing/new_topic", data=post_data)  

这样就可以发帖成功。


看到这里大家一定会想到selenium,是不是和requests一样的? requests更擅长于无UI接口测试,selenium更擅长于有UI的web测试。





  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 我可以提供一些指导,使用Pythonrequests模块发送JSON数据的方法如下:首先,安装requests模块,然后使用requests.post()方法将JSON数据发送到你指定的URL。示例代码如下:import requestsurl = 'http://www.example.com/'data = {'key1': 'value1', 'key2': 'value2'}headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}response = requests.post(url, data=json.dumps(data), headers=headers) ### 回答2: 使用Pythonrequests模块发送JSON数据非常简单。下面是一个示例: 首先,我们需要导入requests模块: import requests 然后,我们可以使用requests的post方法来发送JSON数据: url = "http://example.com/api" # 需要发送JSON数据的API地址 data = {"name": "John", "age": 30} # 要发送的JSON数据 headers = {"Content-Type": "application/json"} # 设置请求头,指定数据格式为JSON response = requests.post(url, json=data, headers=headers) 在上面的代码中,我们将url设置为要发送JSON数据的API地址,将data设置为要发送的JSON数据。同时,我们还指定了请求头Content-Type为application/json,以告知服务器我们发送的是JSON格式的数据。 最后,我们使用requests的post方法发送请求,并将json参数设置为data,headers参数设置为headers。服务器将返回一个response对象,我们可以通过它来获取服务器的响应。 对于发送JSON数据,我们可以使用requests模块的json参数来将数据转换为JSON格式,并自动设置Content-Type为application/json。 以上就是使用Pythonrequests模块发送JSON数据的简单示例。使用requests模块可以轻松地向服务器发送JSON数据,并处理服务器的响应。 ### 回答3: 使用pythonrequests模块发送JSON数据非常方便。 首先,需要导入requests模块:import requests 然后,准备要发送的JSON数据,可以将字典转换为JSON字符串,例如:data = {"name": "小明", "age": 18} 接下来,使用requests模块的post方法发送JSON数据,同时指定请求头的Content-Type为application/json,例如: response = requests.post(url, json=data, headers={"Content-Type": "application/json"}) 其中,url为要发送请求的URL地址,data为要发送的JSON数据,headers为请求头。 最后,可以通过response对象获取服务器的响应结果。例如,可以通过response.text来获取响应的文本结果,response.json()来获取响应的JSON结果。 完整的代码示例: import requests data = {"name": "小明", "age": 18} url = "http://example.com/api" response = requests.post(url, json=data, headers={"Content-Type": "application/json"}) if response.status_code == 200: print("请求成功") print(response.text) print(response.json()) else: print("请求失败") 以上就是使用pythonrequests模块发送JSON数据的简单示例。希望能对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值