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破解ZIP或RAR压缩文件密码

如何使用Python破解ZIP或RAR压缩文件密码

这篇文章主要介绍了如何使用Python破解ZIP或RAR压缩文件密码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 我们经常会从网络...

NumPy 基本切片和索引的具体使用方法

索引和切片是NumPy中最重要最常用的操作。熟练使用NumPy切片操作是数据处理和机器学习的前提,所以一定要掌握好。 文档:https://docs.scipy.org/doc/num...

如何修复使用 Python ORM 工具 SQLAlchemy 时的常见陷阱

在使用 SQLAlchemy 时,那些看似很小的选择可能对这种对象关系映射工具包的性能产生重要影响。 对象关系映射Object-relational mapping(ORM)使应用程序开...

python实现dict版图遍历示例

复制代码 代码如下:#_*_coding:utf_8_import sysimport os class Graph():    def __init__(...

Python 转换文本编码实现解析

最近在做周报的时候,需要把csv文本中的数据提取出来制作表格后生产图表。 在获取csv文本内容的时候,基本上都是用with open(filename, encoding ='UTF-8...