requests模块基本信息
requests模块的作用
发送http请求,获取响应数据
requests安装
pip install requests
requests发送GET请求(使用.encoding指定编码)
# 导入库
import requests
# 目标URL
url = 'https://www.baidu.com'
# 创建实例,发送请求
res = resquests.get(url)
# 设置编码 (utf-8/gbk/gb2312/ascii/iso-8859-1)
res.encoding = 'utf8'
res.content.decode('GBK')
# 打印内容
print(res.text)
response响应对象其他属性
# 导入库
import requests
# 目标URL
url = 'https://www.baidu.com'
# 创建实例,发送请求
res = resquests.get(url)
# 状态码
res.status_code
# 请求头
res.request.heards
# 响应头
res.heards
# 请求Cookie值
res.request._cookies
# 响应Cookie值
res.cookies
# 响应内容转化为json字符
res.json()
requests 发送参数请求(伪装浏览器)
# 导入库
import requests
# 目标URL
url = 'https://www.baidu.com/s?'
# 创建请求头
headers = {
# 浏览器请求
# 浏览器参数
}
# 构建Cookie字典
cook_str = "# cookie值"
cook_list = cook_str.split(';') # 切割
cook_dict = {}
for cookie in cook_list:
cook_dict[cookie.split('=')[0]]=cookie.split('=')[-1] # 赋值获取
# 构建参数
data = {
'wd':'python'
}
# 创建实例,发送请求
res = resquests.get(url = url,headers = headers,params = data,cookuies=cook_dict)
# 打印内容
print(res.content)
cookiejar 转换 cookies字典
# jar转字典
dict_cookies = requests.utils.dict_from_cookiejar(res.cookies) # 丢失域名
# 字典转jar
jar_cookies = requests.utils.cookiejar_from_dict(dict_cookies) # 丢失域名
超时参数timeout
res = requests.get(url, timeout = 3) # 设置3秒内无法进入URL时,返回
代理Proxy使用
代理分类(匿名程度)
透明代理:可以看到真实IP
REMOTE_ADOR = Proxy IP
HTTP_VIA = Proxy IP
HTTP_X_FORWARDED_FOR = Your IP # 真实IP
匿名代理:无法知道真实IP,但可以得知使用代理
REMOTE_ADOR = Proxy IP
HTTP_VIA = Proxy IP
HTTP_X_FORWARDED_FOR = Proxy IP # 代理IP
高匿代理:无法知道是否使用代理及真实IP
REMOTE_ADOR = Proxy IP
HTTP_VIA = not determind # 不定义
HTTP_X_FORWARDED_FOR = not determind # 不定义
代理分类(服务协议)
http代理:目标url为http协议
https代理:目标url为https协议
socks隧道代理:不关心协议种类
代理参数使用
# proxies = {
"http":"http://ip:端口号",
"https":"https://ip:端口号"
}
res = requests.get(url, proxies = proxies) # 设置代理字典
Verify参数使用
# verify使用
res = requests.get(url, verify = False) # 关闭认证
使用resquests.session,状态保持
# 创建实例
session = requests.session()
res = session.get(url, headers,各种参数) # 创建get请求
res = session.post(url, headers,各种参数) # 创建post请求