python3 requests模块用法实例

requests是通过urllib3实现自动发送HTTP/1.1请求,它能轻松的实现cookies,登陆验证,代理设置等操作。

Python内置的urllib模块,用于访问网络资源。但是,它用起来比较麻烦,而且,缺少很多实用的高级功能。
更好的方案是使用requests。它是一个Python第三方库,处理URL 资源特别方便

requests实现内容:

保持活力和连接池支持国际域名和网址会话与Cookie持久性浏览器式SSL验证
自动内容解码基本/摘要式身份验证自动解压缩Unicode响应body
HTTP(s)代理支持多部分文件上传流媒体下载连接超时
分块的请求.netrc 支持  
    

requests并不是python默认安装的,没安装使用pip install requests安装便是。request依赖包关系

requests==2.19.1
  - certifi [required: >=2017.4.17, installed: 2018.4.16]  #CA认证模块
  - chardet [required: <3.1.0,>=3.0.2, installed: 3.0.4]  #通用字符编码检测器模块
  - idna [required: <2.8,>=2.5, installed: 2.7]  #国际化域名解析模块
  - urllib3 [required: <1.24,>=1.21.1, installed: 1.23] #线程安全HTTP库

下面是requests使模块使用实例

requests.request(method,url,**kwargs):构造并发送一个request,返回一个response对象
参数:

method:  request对象的方法(POST)
url:  request对象的URL
params:可选的,要在查询字符串中发送的字典或字节request
data:可选的,字典或元祖列表以表单编码,字节或类似文件的对象在主体中发送[(key,value)]
json:可选的,一个json可序列化的python对象,在主体中发送request
headers:可选的,用于编写http头信息
cookies:可选,用dict或cookieJar对象发送Cookies
file:可选,用于多部分编码上传的字典,可以是多元祖,其中是定义给定文件的内容类型的字符串,以及包含问文件添加的额外头文件的类字典对象
auth:可选,身份验证元祖,自定义http身份验证
timeout:可选,发送等待请求数据的超时时间(float/tuple),设置为元祖即为练级connect和read读取超时,如果设置为None即为永久等待
allow_redirects:布尔值,可选,启用或禁用GET,OPTIONS,POST,PUT,PATCH,DELETE,HEAD重定向,默认为true
proxies:可选,字典映射协议到代理的URL
verify:可选,可以是布尔值,可以指定验证服务器的TLS证书路径,默认为true
stream:可选,如果是False,响应内容将立即下载
cert:可选,如果是string,则为ssl客户端证书文件路径,如果是元祖则('cert','key')指定证书和密钥
# Response对象包含服务器对HTTP请求的响应信息 
import requests
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36'}
r=requests.get('http://docs.python-requests.org/en/master/',headers=headers)
print('chardet提供的编码:',r.apparent_encoding)
print('响应字节内容:',r.content)
print('响应cookies:',r.cookies.items())
print('请求到响应之间的时间:',r.elapsed)
print('响应编码:',r.encoding)
print('响应头信息:',r.headers)
print('头信息中的server:',r.headers['Server'])
print('请求历史记录:',r.history)
print('迭代响应数据:',r.iter_lines())
#print('响应json编码数据:',r.json())
print('返回解析的响应头链接:',r.links)
print('返回状态码:',r.status_code)
print('响应str内容:',r.text)
print('响应URL:',r.url)
print('返回发送的头参数:',r.request.headers)

1.get获取网页内容

from requests import get
response=get('http://httpbin.org/get',params={'name':'py.qi','age':22})#添加参数查询
print(response.text) #返回结果包含args参数,headers头信息,URL和IP信息
print(response.url) #返回组合的URL(http://httpbin.org/get?name=py.qi&age=22)
print(response.json()) #如果返回网页是JSON格式,可以使用json()方法解析返回字典数据
# requests.head(url,**kwargs):发送head请求,url:网站URL地址,返回一个response对象
from requests import head
header=head('https://github.com/get')
print('text:',header.text) #不会返回内容信息
print('headers:',header.headers) #返回头信息
print(header.cookies.items()) #返回cookies元组列表
import requests
import re
url='http://www.runoob.com/python3/python3-reg-expressions.html'
headers={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36'
}
response=requests.get(url,headers=headers)
response.encoding='UTF-8'
#print(response.encoding)
#print(response.text)
pattern = re.compile('id="content">.*?<h1>(.*?)</h1>.*?<p>(.*?)</p><p>(.*?)</p>.*?<p>(.*?)</p>.*?<p>(.*?)</p>.*?<p>(.*?)</p>',re.S)
text = re.search(pattern,response.text)
 
for i in text.groups():
    print(i)

 

Python3 正则表达式
正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。
Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。
re 模块使 Python 语言拥有全部的正则表达式功能。 
compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。 
re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。
# 抓取二进制文件:图像,BytesIO创建内存对象存储数据,Image打开图像获得图像对象,也可以用上下问方式
# 将图像直接写入文件,适合音频,视频等文件
import requests
from io import BytesIO
from PIL import Image
 
url='http://docs.python-requests.org/en/master/_static/requests-sidebar.png'
r=requests.get(url)
i=Image.open(BytesIO(r.content)) #获得一个图像对象
print(i.format,i.size,i.mode) #查看图像的来源,像素和像素类型(RGB)
#print(i.show())  #显示图片
i.save('requests_log.png')  #保存图像数据到文件

2.post方式获取数据

import requests
data={'k1':'v1','k2':'v2'}
r = requests.post('http://httpbin.org/post',data=data) #以表单数据发送数据
body=r.json()  #获得字典格式的返回数据 
print(body['form'])  #窃取表单编码数据
# 多个文件上传
import requests
 
url='http://httpbin.org/post'
 
multple_files=[
    ('images1',('11.jpg',open('11.jpg','rb'),'image/jpg')),
    ('images2',('22.jpg',open('22.jpg','rb'),'image/jpg')),
]  #字段代表意思依次为:文件名,文件对象,文件类型
r=requests.post(url,files=multple_files)
print(r.text)
# 上传文件:files参数指定上传文件,上传的文件在主体数据中
 
import requests
url='http://httpbin.org/post'
files={'file':open('network.csv','rb')}
files1={'file':('filename.xls',open('fileanme.xls','rb'),'application/vnd.ms-excel',{'expires':'0'})} #设置文件名
r=requests.post(url,files=files) #指定文件发送请求
print(r.json()['files'])

3.添加数据头

有时网站可能限制了user agent(UA),你直接用默认参数使用的UA是包含了requests的,所以如果修改头的话就是

import requests
headers = {'user-agent': 'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10'}
url="https://httpbin.org/get"
r = requests.get(url, headers=headers,timeout=5)
    #或者使用timeout设置延时

4.基础验证

有的时候如果网站使用了基础验证的话,只需要添加auth参数即可

r = requests.get(url, headers=headers,timeout=5,auth=HTTPBasicAuth('username', 'password'))
    #由于httpbasicauth比较普遍,python允许不谢验证方法,如下
r = requests.get(url, headers=headers,timeout=5,auth=('username', 'password'))

5.get下载文件

r = requests.get('https://www.bobobk.com/wp-content/uploads/2018/12/wizard.webp')
f = open('download.webp', 'wb')
for chunk in r.iter_content(chunk_size=512 * 1024): 
	if chunk: 
		f.write(chunk)
f.close()

此处使用的方法可以下载大文件

6.post下载文件

当然也是可以直接post文件的,添加参数files,用法

url = 'https://httpbin.org/post'
files = {'file': ('myfile.xls', open('myfile.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)

7.使用cookie

直接指定cookie参数即可

url = 'https://httpbin.org/cookies'
r = requests.get(url, cookies={"username":"bobobk"})
    #如果是网页返回包含cookie,也可以方便的获取到cookie
r.cookies

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值