Requests模块简单入门

#HTTP请求类型
#get类型
r = requests.get(‘https://github.com/timeline.json‘)
#post类型
r = requests.post("http://m.ctrip.com/post")
#put类型
r = requests.put("http://m.ctrip.com/put")
#delete类型
r = requests.delete("http://m.ctrip.com/delete")
#head类型
r = requests.head("http://m.ctrip.com/head")
#options类型
r = requests.options("http://m.ctrip.com/get")

#获取响应内容
print r.content #以字节的方式去显示,中文显示为字符
print r.text #以文本的方式去显示

#URL传递参数
payload = {‘keyword‘: ‘日本‘, ‘salecityid‘: ‘2‘}
r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload)
print r.url #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=日本

#获取/修改网页编码
r = requests.get(‘https://github.com/timeline.json‘)
print r.encoding
r.encoding = ‘utf-8‘

#json处理
r = requests.get(‘https://github.com/timeline.json‘)
print r.json() #需要先import json    

#定制请求头
url = ‘http://m.ctrip.com‘
headers = {‘User-Agent‘ : ‘Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19‘}
r = requests.post(url, headers=headers)
print r.request.headers

#复杂post请求
url = ‘http://m.ctrip.com‘
payload = {‘some‘: ‘data‘}
r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下

#post多部分编码文件
url = ‘http://m.ctrip.com‘
files = {‘file‘: open(‘report.xls‘, ‘rb‘)}
r = requests.post(url, files=files)

#响应状态码
r = requests.get(‘http://m.ctrip.com‘)
print r.status_code

#响应头
r = requests.get(‘http://m.ctrip.com‘)
print r.headers
print r.headers[‘Content-Type‘]
print r.headers.get(‘content-type‘) #访问响应头部分内容的两种方式

#Cookies
url = ‘http://example.com/some/cookie/setting/url‘
r = requests.get(url)
r.cookies[‘example_cookie_name‘]    #读取cookies

url = ‘http://m.ctrip.com/cookies‘
cookies = dict(cookies_are=‘working‘)
r = requests.get(url, cookies=cookies) #发送cookies

#设置超时时间
r = requests.get(‘http://m.ctrip.com‘, timeout=0.001)

#设置访问代理
proxies = {
           "http": "http://10.10.10.10:8888",
           "https": "http://10.10.10.100:4444",
          }
r = requests.get(‘http://m.ctrip.com‘, proxies=proxies)

4、Requests示例

json请求

 1 #!/user/bin/env python
 2 #coding=utf-8
 3 import requests
 4 import json
 5
 6 class url_request():
 7     def __init__(self):
 8             """ init """
 9
10 if __name__==‘__main__‘:
11     headers = {‘Content-Type‘ : ‘application/json‘}
12     payload = {‘CountryName‘:‘中国‘,
13                ‘ProvinceName‘:‘陕西省‘,
14                ‘L1CityName‘:‘汉中‘,
15                ‘L2CityName‘:‘城固‘,
16                ‘TownName‘:‘‘,
17                ‘Longitude‘:‘107.33393‘,
18                ‘Latitude‘:‘33.157131‘,
19                ‘Language‘:‘CN‘
20                }
21     r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity",headers=headers,data=payload)
22     #r.encoding = ‘utf-8‘
23     data=r.json()
24     if r.status_code!=200:
25         print "LBSLocateCity API Error " + str(r.status_code)
26     print data[‘CityEntities‘][0][‘CityID‘] #打印返回json中的某个key的value
27     print data[‘ResponseStatus‘][‘Ack‘]
28     print json.dumps(data,indent=4,sort_keys=True,ensure_ascii=False) #树形打印json,ensure_ascii必须设为False否则中文会显示为unicode

xml请求

#!/user/bin/env python
#coding=utf-8
import requests

class url_request():
    def __init__(self):
            """ init """    

if __name__==‘__main__‘:

    headers = {‘Content-type‘: ‘text/xml‘}
    XML = ‘<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>‘
    url = ‘http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx‘
    r = requests.post(url,headers=headers,data=XML)
    #r.encoding = ‘utf-8‘
    data = r.text
    print data

5、参考文档

http://cn.python-requests.org/en/latest/

http://docs.python-requests.org/en/latest/user/quickstart.html

原文地址:https://www.cnblogs.com/daluozi/p/9569132.html

时间: 2024-07-31 14:20:03

Requests模块简单入门的相关文章

requests模块的入门使用

学习目标: 了解 requests模块的介绍 掌握 requests的基本使用 掌握 response常见的属性 掌握 requests.text和content的区别 掌握 解决网页的解码问题 掌握 requests模块发送带headers的请求 掌握 requests模块发送带参数的get请求 1 为什么要重点学习requests模块,而不是urllib requests的底层实现就是urllib requests在python2 和python3中通用,方法完全一样 requests简单易

requests模块简单学习(一)

requests模块安装resquests模块py -2 -m pip install requestspy -3 -m pip install requestsget方法get请求使用的是requests模块已经封装好的get方法,该方法的原型为:get(url, params=None, kwargs) 发送一个get请求参数说明:url:请求的urlparams:传递查询的参数,可以是字典类型,也可以是bytes类型.kwargs:可选请求参数该方法返回一个reponse对象.示例1: i

requests模块简单用法

1 import requests 2 import random 3 4 # 请求发送的网址url 5 url = 'https://www.baidu.com' 6 # 请求头信息,通常用于伪装浏览器,通过服务器校验 7 headers = { 8 9 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safa

Python高手之路【八】python基础之requests模块

1.Requests模块说明 Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写,真正的为人类着想. Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了.它是为另一个时代.另一个互联网所创建的.它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务. 在Python的世界里,事情不应该这么麻烦. Requests 使用的是 urllib3,因此继承了它的所有特性.Request

Python requests模块学习笔记

1.Requests模块说明 Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写,真正的为人类着想. Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了.它是为另一个时代.另一个互联网所创建的.它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务. 在Python的世界里,事情不应该这么麻烦. Requests 使用的是 urllib3,因此继承了它的所有特性.Request

7Python标准库系列之requests模块

Python标准库系列之requests模块 Requests is the only Non-GMO HTTP library for Python, safe for human consumption. 官方文档:http://docs.python-requests.org/en/master/ 安装Requests模块 Requests模块官方提供了两种方式安装: pip方式安装 pip install requests 源码方式安装 git clone git://github.co

超级简单的requests模块教程

在web后台开发过程中,会遇到需要向第三方发送http请求的场景,python中的requests库可以很好的满足这一要求,这里简要记录一下requests模块的使用! 说明: 这里主要记录一下requests模块的如下几点: 1.requests模块的安装 2.requests模块发送get请求 3.requests模块发送post请求 4.requests模块上传文件 requests模块的安装 requests模块数据第三方库,这里使用pip进行安装: pip install reques

python之requests模块

Python标准库中提供了:urllib等模块以供Http请求,但是,它的 API 太渣了.它是为另一个时代.另一个互联网所创建的.它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务. 发送GET请求 import urllib.request f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')

Nginx模块开发入门(转)

前言 Nginx是当前最流行的HTTP Server之一,根据W3Techs的统计,目前世界排名(根据Alexa)前100万的网站中,Nginx的占有率为6.8%.与Apache相比,Nginx在高并发情况下具有巨大的性能优势. Nginx属于典型的微内核设计,其内核非常简洁和优雅,同时具有非常高的可扩展性.Nginx最初仅仅主要被用于做反向代理,后来随着HTTP核心的成熟和各种HTTP扩展模块的丰富,Nginx越来越多被用来取代Apache而单独承担HTTP Server的责任,例如目前淘宝内