爬虫之requests模块发送get/post请求
目录
爬虫介绍
爬虫就是程序从互联网中各个网站上爬取数据,做数据清洗再入库。
爬虫的本质:模拟方式http请求,获取数据再入库。
百度其实是一个大爬虫,百度爬虫一刻不停的在互联网中爬取各个页面,爬完保存到数据库中。在百度搜索框中搜索,百度首先在数据库查询关键字获取数据,返回回来---点击某个页面---》跳转到真正的地址上
爬虫
# 模拟发送http请求
# 爬虫模块
1.requests模块
2.selenium
网页反扒:封id:ip代理 ,封账号:cookie池
# 解析数据模块
1.BeautifulSoup4--bs4模块
2. pyquery模块
3.爬虫框架--scrapy
# 数据入库
1.mysql
2.redis
3.文件中
requests模块介绍
使用python如何向网页发送http请求,本质是requests模块,封装了python内置模块urllib,使用requests可以模拟浏览器的请求(http),比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)
# 安装
pip3 install requests
request发送get请求
import requests
# res = requests.get('https://www.cnblogs.com/zhanglanhua/p/17217208.html')
# print(res) # <Response [200]>
# print(res.text) # 文本
# 如果有的网站,发送请求,不返回数据,人家做了反扒---》拿不到数据,学习如何反扒
res = requests.get('https://dig.chouti.com/')
print(res.text) # 反扒--访问不了
request携带参数
import requests
# 方式一:直接拼到路径中
# res = requests.get('https://www.cnblogs.com/zhanglanhua/p/17217208.html?name=kimi&age=19')
# print(res.text)
# 方式2:使用params参数
"""
def get(url, params=None, **kwargs):
pass
"""
res = requests.get('https://www.cnblogs.com/zhanglanhua/p/17217208.html',params={
'name':'kimi','age':18
})
print(res.text)
print(res.url) # https://www.cnblogs.com/zhanglanhua/p/17217208.html?name=kimi&age=18
url编码解码--urllib
import requests
from urllib.parse import quote,unquote # 编码与解码
res = requests.get('https://www.cnblogs.com/zhanglanhua/p/17217208.html',params={
'name':'董卿','age':18
})
print(res.url) # https://www.cnblogs.com/zhanglanhua/p/17217208.html?name=%E8%91%A3%E5%8D%BF&age=18
# 如果是中文,在地址栏中会做url的编码:董卿:%E8%91%A3%E5%8D%BF
# 编码
res = quote('董卿')
print(res) # %E8%91%A3%E5%8D%BF
res = unquote('%E8%91%A3%E5%8D%BF')
print(res) #董卿
反扒措施
http协议版本的区别
2.0 比1.0多了多路复用,将多个请求基于底层TCP流式协议,可以将多个请求一起发送。
# http协议版本间的区别
# Connection: keep-alive
# http协议有版本:主流1.1 0.9 2.x
# http 基于TCP 如果建立一个http链接---》底层创建一个tcp链接
# 1.1比之前多了keep-alive
# 2.x比1.x多了 多路复用
携带请求头
http请求中,请求头中有一个很重要的参数 :User-Agent,如果向后端发送请求没有带这个请求头,后端就禁止访问。大多网站没有携带该参数就被禁止了。
用户代理(User Agent,简称 UA),是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等。
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36
import requests
# http请求头:User-Agent,cookie,Connection
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
}
# res = requests.get('https://dig.chouti.com/') # 不带访问不进去
res = requests.get('https://dig.chouti.com/',headers=headers)
print(res.text)
print(res.url) # https://dig.chouti.com/
发送post请求,携带登录信息
import requests
# 携带登录信息---cookie
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
'Cookie':''
}
# post携带数据
data={
'linkId':'38063872'
}
res = requests.post('https://dig.chouti.com/',headers=headers,data=data)
print(res.text)
print(res.url) # https://dig.chouti.com/
# 双token认证
自动登录--携带cookie的两种方式
登录功能,一般是post请求
import requests
data = {
'username': '',
'password': '',
'captcha': '3456',
'remember': 1,
'ref': 'http://www.aa7a.cn/',
'act': 'act_login'
}
res = requests.post('http://www.aa7a.cn/user.php',data=data)
print(res.text)
# 响应中会有登录成功的的cookie,
print(res.cookies) # RequestsCookieJar 跟字典一样
# 拿着这个cookie,发请求,就是登录状态
# 访问首页,get请求,携带cookie,首页返回的数据一定会有 我的账号
# 携带cookie的两种方式 方式一是字符串,方式二是字典或CookieJar对象
# 方式二:放到cookie参数中
res1=requests.get('http://www.aa7a.cn/',cookies=res.cookies)
print('616564099@qq.com' in res1.text)
requests.session 的使用
import requests
data = {
'username': '',
'password': '',
'captcha': '3456',
'remember': 1,
'ref': 'http://www.aa7a.cn/',
'act': 'act_login'
}
session = requests.session()
res = session.post('http://www.aa7a.cn/user.php', data=data)
print(res.text)
res1 = session.get('http://www.aa7a.cn/') # 自动保持登录状态,自动携带cookie
print('616564099@qq.com' in res1.text)
post请求携带数据编码格式
import requests
# data对应字典,这样写,编码方式是urlencoded
requests.post(url='xxxxxxxx',data={'xxx':'yyy'})
# json对应字典,这样写,编码方式是json格式
requests.post(url='xxxxxxxx',json={'xxx':'yyy'})
# 终极方案,编码就是json格式
requests.post(url='',
data={'':1,},
headers={
'content-type':'application/json'
})
响应Response对象
# Response相应对象的属性和方法
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}
respone=requests.get('http://www.jianshu.com',headers=headers)
# respone属性
print(respone.text) # 响应体转成了字符串
print(respone.content) # 响应体的二进制内容
print(respone.status_code) # 响应状态码
print(respone.headers) # 响应头
print(respone.cookies) # cookie是在响应头,cookie很重要,它单独做成了一个属性
print(respone.cookies.get_dict()) # cookieJar对象---》转成字段
print(respone.cookies.items()) # cookie的键值对
print(respone.url) # 请求地址
print(respone.history) # 不用关注
print(respone.encoding) # 响应编码格式
编码问题
# 有的网站,打印
res.text --->发现乱码---》请求回来的二进制---》转成了字符串---》默认用utf8转---》
response.encoding='gbk'
再打印res.text它就用gbk转码
下载图片视频
import requests
# 下载图片
res=requests.get(' https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fci.xiaohongshu.com%2Fb89bafc3-0684-ae14-46c7-dac94c184418%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fci.xiaohongshu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto')
# print(res.content)
with open('111.jpg','wb') as f:
f.write(res.content)
# 下载视频
res=requests.get('https://vd3.bdstatic.com/mda-pcdcan8afhy74yuq/sc/cae_h264/1678783682675497768/mda-pcdcan8afhy74yuq.mp4')
with open('123.mp4','wb') as f:
for line in res.iter_content():
f.write(line)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY