Python常用模块之requests模块用法分析

yipeiwu_com6年前Python基础

本文实例讲述了Python常用模块之requests模块用法。分享给大家供大家参考,具体如下:

一. GET请求

1.访问一个页面

import requests
r=requests.get('http://www.so.com')
print(r.status_code)
print(r.text)

2.带参数

import requests
params = {'a':1,'b':2}
r=requests.get('http://www.so.com', params=params)
print(r.url)

3.返回数据显示

import requests
r = requests.get('https://pullwave.com/pw2/api/acc_query_words?auth_usr=free_vip&src=s0&w1=%E6%8A%96%E9%9F%B3&w2=&date_end=2019-4-6&json=1')
print(r.content)
print(r.text)
print(r.json())
print(r.headers)

4.请求头

import requests
r = requests.get('https://pullwave.com/pw2/api/acc_query_words?auth_usr=free_vip&src=s0&w1=%E6%8A%96%E9%9F%B3&w2=&date_end=2019-4-6&json=1', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'})
print(r.content)
print(r.text)
print(r.json())

二.POST请求

1.传参

r = requests.post('http://www.so.com', data={'fdsafdfs': 'fsdsfa', 'fdsfs': 'dfsfs'})

2.传json

params = {'key': 'value'}
r = requests.post(url, json=params)

3.传文件

upload_files = {'file': open('234.txt', 'rb')}
r = requests.post(url, files=upload_files)

4.带cookie

url = 'http://www.so.com'
cs = {'lalala': 'lalala', 'lallala': '23232'}
r = requests.get(url, cookies=cs)

5.超时

r = requests.get(url, timeout=5)

详细用法:
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

对Python的Django框架中的项目进行单元测试的方法

 Python中的单元测试 我们先来回顾一下Python中的单元测试方法。 下面是一个 Python的单元测试简单的例子: 假如我们开发一个除法的功能,有的同学可能觉得很简单,...

Python与Java间Socket通信实例代码

Python与Java间Socket通信   之前做过一款Java的通讯工具,有发消息发文件等基本功能.可大家也都知道Java写的界面无论是AWT或Swing,那简直不是人看的,对于我们...

Python使用QRCode模块生成二维码实例详解

Python使用QRCode模块生成二维码 QRCode官网 https://pypi.python.org/pypi/qrcode/5.1 简介 python-qrcode是个用来...

SublimeText 2编译python出错的解决方法(The system cannot find the file specified)

[Error 2] The system cannot find the file specified 解决方法:1.环境变量path添加:C:\Python32\Tools\Scrip...

python中嵌套函数的实操步骤

python中嵌套函数的实操步骤

在python中如何嵌套函数? 首先打开python编辑器并且写上注释的内容。 然后定义一个函数addstr 在addstr函数里面写上内容,内容是写入文件内容。 新建第二个函数...