requests库请求

news/2024/7/19 12:38:11 标签: json, 爬虫, python

请求requests

参考:

http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced

 

首先要导入:import requests
r = requests.post('http://httpbin.org/post', data=payload) #post请求,参数格式为from
r = requests.post('http://httpbin.org/post', json=payload) #post请求,参数格式为json

r = requests.get('http://httpbin.org/get') #单纯的GET请求
r = requests.get("http://httpbin.org/get", params=payload) #带参数的get请求
r = requests.get('https://api.github.com/some/endpoint', headers={'user-agent': 'my-app/0.0.1'}) #带头参数的get请求
r = requests.get('http://github.com', timeout=0.001) #带超时判断的get请求
r = requests.get('http://httpbin.org/cookies', cookies=cookies) #带cookies参数的get请求

其他:
>>> r = requests.put('http://httpbin.org/put', data = {'key':'value'}) #从客户端向服务器传送的数据取代指定的文档的内容
>>> r = requests.delete('http://httpbin.org/delete') #请求服务器删除指定的页面
>>> r = requests.head('http://httpbin.org/get') #只请求页面的首部
>>> r = requests.options('http://httpbin.org/get')


返回内容还有其它更多信息
-- r.url # 获取url
-- r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
-- r.encoding #编码格式,可以用r.encoding = 'utf-8'来定义编码格式
-- r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩.py3是r.content.decode
-- r.json() #Requests中内置的JSON解码器
-- r.raw #返回原始响应体,请求里添加stream=True属性

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

-- r.status_code #响应状态码
-- r.raise_for_status() #失败请求(非200响应)抛出异常


文件上传:
使用files参数,files指向一个dict字典,字典的键是'文件名',而值是打开这个文件读取到内存的内容。一般用post请求
例子:
cur_path = os.path.dirname(os.path.realpath(__file__)) #获得所引用的模块 所在的绝对路径
filePath = os.path.join(cur_path + r"\imgs\4.jpg") #组成一个绝对路径
files = {'companyLogo': open(filePath, 'rb')} #files字典
headers = {'Content-Disposition': 'form-data'}
r = requests.post(SaveImg.host + SaveImg.url + '/saveImg', files=files, headers=headers)

文件下载
使用stream = True控制下载动作,获取字节content用write方法把下载内容写入path这个路径里面
url = 'http://docs.python-requests.org/zh_CN/latest/_static/requests-sidebar.png'
path = 'C:/Users/ms/Downloads/test.jpg'
r = requests.get(url,stream = True)
with open(path,'wb') as f: #创建一个上下文管理器对象f,执行f.write(r.content),不管是否报错最后都会释放资源
f.write(r.content) #相当于try:finally:

重定向状态码:
--301 redirect: 301 代表永久性转移(Permanently Moved)
--302 redirect: 302 代表暂时性转移(Temporarily Moved )
重定向地址放在head返回信息的:Location里面
r = s.get('https://i.cnblogs.com/EditPosts.aspx?opt=1',
headers=headers,
# allow_redirects=True, #启动重定向
allow_redirects=False, #关闭重定向
verify=False,
)
print(r.history) #使用r.history查看重定向历史

获取cookie
直接调用r.cookies即可得到返回值
获取cookie的某一个值:r.cookies['NID']

消除警告信息
from requests.packages import urllib3
urllib3.disable_warnings() #这条命令主要用于消除警告信息

代理设置

在进行爬虫爬取时,有时候爬虫会被服务器给屏蔽掉,这时采用的方法主要有降低访问时间,通过代理ip访问,
如下:

import requests

proxies = {
"http": "http://127.0.0.1:9743",
"https": "https://127.0.0.1:9743",
}


response = requests.get("https://www.taobao.com", proxies=proxies)
print(response.status_code)
ip可以从网上抓取,或者某宝购买

如果代理需要设置账户名和密码,只需要将字典更改为如下:
proxies = {
"http":"http://user:password@127.0.0.1:9999"
}
如果你的代理是通过sokces这种方式则需要pip install "requests[socks]"
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}

认证设置

如果碰到需要认证的网站可以通过requests.auth模块实现
response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
print(response.status_code)

转载于:https://www.cnblogs.com/lijinglj/p/9646159.html


http://www.niftyadmin.cn/n/682484.html

相关文章

怎样在网页中画一条竖线?

怎样在网页中画一条竖线&#xff1f; 2014-03-13 09:24 7534人阅读 评论(0) 收藏 举报 分类&#xff1a; 【毕业设计】&#xff08;16&#xff09; hr横线&#xff1a;<hr size"1" color"#999999">竖线&#xff1a;<hr size100 width"1&qu…

自定义 java 加载器

先写个java类的&#xff1a;allen.java import java.util.Date; import java.util.List;/*** 加载类* author Administrator*/ public class allen extends Date{// private static final long serialVersionUID 8627644427315706176L;//打印数据Overridepublic String toStri…

cad在线转换_CAD、JPG、PDF、DXF被秒速玩转,到底有多厉害?看完操作就知道

一秒教你玩转CAD、JPG、PDF、DXF、DWG格式转换&#xff0c;轻巧玩转办公格式转换操作&#xff0c;各类格式转换烦恼轻松解决&#xff01;具体有多厉害&#xff1f;这里分享给你详细的操作步骤&#xff0c;三种操作方法教你轻松解决&#xff0c;无论是哪一种操作步骤你都能够用的…

Flutter环境搭建之pod setup安装慢解决办法

背景 今年6月份的时候在GMTC2018全球大前端技术大会见识到了由google工程师展示的Flutter&#xff0c;一下就被迷住了。flutter使用dart语法编写跨平台的原生应用&#xff0c;dart语法像极了Typescript所以我觉得一个有着javascript && Typescript功底的人肯定能很快的…

xp扩容C盘后盘符丢失的资料怎么找到

调整分区后盘符不见是比较常见的数据恢复案例&#xff0c;需要注意&#xff0c;调整分区后盘符不见后不要再重建新的分区。保护好文件丢失现场&#xff0c;可以最大程度的恢复出文件。具体的恢复方法看正文了解。 工具/软件&#xff1a;AuroraDataRecovery 步骤1&#xff1a;先…

核心频率个加速频率_RTX 3090液氮超频可将核心频率推高到2580MHz

在新的地表最强游戏显卡RTX 3090上市才不久&#xff0c;就有超频大神开始对这张显卡进行疯狂的性能压榨了。借助液氮散热&#xff0c;超频大神Vince Lucido将一张EVGA RTX 3090 Kingpin显卡核心频率推高到2580MHz&#xff0c;显存频率推高到了21.5Gbps&#xff0c;比标准规格的…

upupw kangle 504 错误调试 服务器拒绝了链接

upupw kangle 504 错误调试 1.先看日志 upupw\Kangle\var\server.log 2 Fri 25 Mar 19:40:04|cannt accept connect,errnoNo error Fri 25 Mar 19:40:04|cannt accept connect,errnoNo error 3 不是拒绝了链接&#xff0c;就是链接已重置&#xff0c;需要修改面板09进入k后…

计算机网络自顶向下方法第七版 英文pdf_FPGA学习altera系列: 第二篇 数字系统设计思想方法以及软件基本操作...

大侠好&#xff0c;欢迎来到FPGA技术江湖&#xff0c;江湖偌大&#xff0c;相见即是缘分。大侠可以关注FPGA技术江湖&#xff0c;在“闯荡江湖”、"行侠仗义"栏里获取其他感兴趣的资源&#xff0c;或者一起煮酒言欢。今天给大侠带来“FPGA学习系列altera"系列&a…