requests模块
Posted jfxu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了requests模块相关的知识,希望对你有一定的参考价值。
import requests
# GET请求
url = 'http://httpbin.org/get'
r = requests.get(url)
print(r.status_code,r.reason)
print(r.text)
# GET带参数请求
r = requests.get(url,params={'a':1,'b':2})
print(r.json())
# POST请求
url = 'http://httpbin.org/post'
r = requests.post(url,data={'a':1})
print(r.json())
# 自定义headers请求
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0',
}
url = 'http://httpbin.org/headers'
r = requests.get(url,headers=headers)
print(r.json())
# 带cookie的请求
cookies = dict(userid='1234565',tokern='xxxxxxx')
url = 'http://httpbin.org/cookies'
r = requests.get(url,cookies=cookies)
print(r.json())
# Basic-auth认证登陆请求
url = 'http://httpbin.org/basic-auth/guye/123456'
auth = ('guye','123456')
r = requests.get(url,auth=auth)
print(r.json())
# 主动抛出状态码异常
url = 'http://httpbin.org/status/404'
bad_r = requests.get(url)
print(bad_r.status_code)
bad_r.raise_for_status() # 主动抛出异常
# requests.Session对象请求
url = 'http://httpbin.org/cookies/set/name/jfxu'
# 创建一个Session对象
s = requests.Session()
# Session对象会保存服务器返回的set-cookies头信息里面的内容
# 下次请求时会将本地所有的cookies信息自动添加到请求头信息里面
r = s.get(url)
print(r.json())
# 在requests中使用代理
url = 'http://httpbin.org/ip'
proxies = {
'http':'http://iguye.com:41801'
}
r = requests.get(url,proxies=proxies)
print(r.json())
# 设置请求等待时间
url = 'http://httpbin.org/delay/3'
r = requests.get(url,timeout=2)
print(r.json())
以上是关于requests模块的主要内容,如果未能解决你的问题,请参考以下文章
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段
如何使用模块化代码片段中的LeakCanary检测内存泄漏?
C#-WebForm-★内置对象简介★Request-获取请求对象Response相应请求对象Session全局变量(私有)Cookie全局变量(私有)Application全局公共变量Vi(代码片段
Python练习册 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-),(http://tieba.baidu.com/p/2166231880)(代码片段