python中request模块用法_【python】request模块使用

此处记录Python 第三方Request 模块的使用方法

1.安装

pip安装

pip install requests

2.导入模块

import requests

3.简单使用

Get 请求

发送无参数的get请求,尝试获取某个网页.

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

发送无参数的get请求 设置超时时间 timeout 单位秒

r = requests.get('http://www.meituan.com', timeout=1)

发送带参数的请求.

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

r = requests.get("https://www.baidu.com/", params=payload)

print(r.url)

https://www.baidu.com/?key2=value2&key1=value1

将一个列表作为值传入.

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

r = requests.get('http://www.baidu.com/', params=payload)

print(r.url)

http://www.baidu.com/?key2=value2&key2=value3&key1=value1

定制请求头

url = 'https://www.baidu.com/s?wd=python'

headers = {

'Content-Type': 'text/html;charset=utf-8',

'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'

}

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

Response对象使用.

r.url #打印输出该 URL

r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None

r.status_code #返回连接状态,200正常。

r.text #默认以unicode形式返回网页内容,也就是网页源码的字符串。

r.content #以字节形式(二进制)返回。字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩。

r.json() #把网页中的json数据转成字典并将其返回。

r.encoding #获取当前的编码

r.encoding = 'ISO-8859-1' #指定编码,r.text返回的数据类型,写在r.text之前。

POST 请求

HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式,服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析。具体的编码方式包括:

1.最常见post提交数据的方式,以form表单形式提交数据

application/x-www-form-urlencoded

2.以json串提交数据。

application/json

3.一般使用来上传文件

multipart/form-data

实例如下:

1. 以form形式发送post请求

Reqeusts支持以form表单形式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可

payload = {'key1': 'value1',

'key2': 'value2'

}

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

print(r.text)

...

"form": {

"key1": "value1",

"key2": "value2"

},

...

2. 以json形式发送post请求

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

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

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

#print(r.text)

print(r.headers.get('Content-Type'))

application/json

3. 以multipart形式发送post请求

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

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

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

print(r.text)

{

...

"files": {

"file": "hello world"

},

"form": {},

"headers": {

"Content-Type": "multipart/form-data; boundary=6db46af64e694661985109da21c8fe9b",

},

"json": null,

"origin": "223.72.217.138",

"url": "http://httpbin.org/post"

...

}

https://www.jb51.net/article/133660.htm

https://blog.csdn.net/qq_878799579/article/details/73956344?utm_source=blogxgwz0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值