基础爬虫篇

文章目录

爬虫介绍

python 复制代码
# 爬虫是什么?
	-通过编程技术---》把互联网中的数据---》获取到---》数据清洗---》存到库中
  python:request,selenium---》app,小程序,网站---》xpaht,lxml---》mysql,redis,文件,excel,mongodb
    -通过编程语言---》模拟发送http请求---》获取数据---》解析--》入库
    -爬取过程 解析过程 会遇到反扒
    -抓app,小程序---》抓包工具---》抓取手机发送的所有请求
    	-charles
        -Fiddler
        
# 爬虫 有爬虫协议
	-君子协议
    -https://xxx/robots.txt
# 百度 是个大爬虫
	-百度/谷歌 搜索引擎---》启动了一个爬虫---》一刻不停的在互联网中爬取网站---》存到库中(es)
    -用户在百度输入框中---》输入搜索内容---》去百度的库中搜索--》返回给前端---》前端点击---》去了真正的地址
    
    -seo 优化
    	-不花钱---》搜索关键词的结果---》排的靠前
        -伪静态
    -sem 优化
    	-花钱买关键词

requsets模块和快速使用

python 复制代码
import requests

# gie携带参数
# 第一种 直接写在地址栏中
res = requests.get(
    'https://api.map.baidu.com/place/v2/search?ak=6E823f587c95f0148c19993539b99295&region=上海&query=肯德基&output=json')
print(res.text)

# 第二种
params = {} 
params = {
    'ak': '6E823f587c95f0148c19993539b99295',
    'region': '上海',
    'query': '肯德基',
    'output': 'json',
}

res = requests.get('https://api.map.baidu.com/place/v2/search', params=params)
print(res.text)

# 编码与解码
from urllib.parse import quote,unquote
s='上海'  # %E4%B8%8A%E6%B5%B7
print(quote(s))

print(unquote('%E4%B8%8A%E6%B5%B7'))

携带请求头

python 复制代码
import requests

# 携带请求头 如果程序模拟的不像 访问不到数据
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
res = requests.get('https://dig.chouti.com/',headers=headers)

print(res.text)

携带cookie的两种方式

python 复制代码
# 发送post请求
# 请求头的参数必带
# 携带cookie的第一种方式
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    # 登录之后回返回cookie 没有登录---》返回的数据不是咱们想要的
    'Cookie': 'token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJjdHVfNzA4NjEwMzY4NTkiLCJleHBpcmUiOiIxNzExMjAyMzY4ODAyIn0.TnUYjU6KqR1itEW6QkTSSUfqc48rkT3hnsg4Cvh4XA4; path=/; Max-Age=2592000',
}
# 你点赞作品的id号
data = {
    'linkId': '41601398'
}
# 在请求头中注意点赞的地址
res = requests.post('https://dig.chouti.com/link/vote',headers=headers,data=data)
print(res.text)

# 第二种携带cookie的方式
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
}
data = {
    'linkId': '41600539'
}
cookie = {
    # 如果不成功 继续携带参数测试
    'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJjdHVfNzA4NjEwMzY4NTkiLCJleHBpcmUiOiIxNzExMjAyMzY4ODAyIn0.TnUYjU6KqR1itEW6QkTSSUfqc48rkT3hnsg4Cvh4XA4; path=/; Max-Age=2592000',
}
# 没有登录---》返回的数据不是咱们想要的
res = requests.post('https://dig.chouti.com/link/vote', headers=headers, data=data, cookies=cookie)
print(res.text)

post携带参数

python 复制代码
import requests
# 方式一:data参数:urlencoded
# post请求:三种编码方式:json,urlencoded,form-data
# 咱们以data字典形式携带--->urlencoded编码---》最终它会被编码为---》name=lqz&age=19 -->放在请体中
#data={} res=requests.post('地址',data=data) 
# res=requests.post('地址',data={'name':'lqz','age':19}) 

res=requests.post('地址',data=b'name=lqz&age=19')

# 方式二:json编码:json
# 咱们以json字典形式携带--->json编码---》最终它会被编码为---》{'name':'lqz','age':19} -->放在请体中
res=requests.post('地址',json={'name':'lqz','age':19})

模拟登录 取出cookie和处理cookie

python 复制代码
import requests
# 第一种方式
import requests

data = {
    'username': '616564099@qq.com',
    'password': 'lqz123111',
    'captcha': '3333',
    'remember': '1',
    'ref': ' http://www.aa7a.cn/',  # 你想购买产品但是没登录 登录成功,重定向到这个地址
    'act': 'act_login',
}
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
# 提交数据登录
res = requests.post('http://www.aa7a.cn/user.php', headers=header, data=data)
print(res.text)
# 登录成功的cookie
cookies = res.cookies
print(cookies)

# 向首页发送请求--->登录状态
res = requests.get('http://www.aa7a.cn/', cookies=cookies)
print('616564099@qq.com' in res.text)


# 第二种
import requests
session = requests.session()
# 以后发送请求使用session

data = {
    'username': '616564099@qq.com',
    'password': 'lqz12311',
    'captcha': '3333',
    'remember': '1',
    'ref': ' http://www.aa7a.cn/',  # 登录成功,重定向到这个地址
    'act': 'act_login',
}
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
# session自动获取cookie并且携带过去
res = session.post('http://www.aa7a.cn/user.php', headers=header, data=data)

# 向首页发送请求--->登录状态
res1 = session.get('http://www.aa7a.cn/')

# 登录成功之后可以判断一下用户之后在不在登录页面
print('616564099@qq.com' in res1.text)

响应对象

python 复制代码
# response 对象---》http响应

### 使用requests模块
# 发送请求:request对象:请求头,请求参数,请求体---》本质就是http请求--》被包装成一个对象
# 响应回来:response对象:http响应--》cookie,响应头,响应体。。

# 爬取图片--》图片防盗链---》referfer--》请求头中即可

import requests

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
respone = requests.get('https://www.jianshu.com/',headers=header)
# respone属性
print(respone.text)  # 响应体---》字符串形式

print(respone.content)  # 响应体---》bytes格式

print(respone.status_code)  # 响应状态码

print(respone.headers)  # 响应头
print(respone.cookies)  # 响应的cookie
print(respone.cookies.get_dict())  # cookiejar对象--->转成字典格式
print(respone.cookies.items())  # cookie的value值

print(respone.url)  # 请求地址
print(respone.history)  # 访问历史---》重定向,才会有

print(respone.encoding)  # 编码格式

res = respone.iter_content() # 图片,视频---》迭代着把数据保存到本地

===========================
# 如果下载图片,视频。。。

# 图片防盗链---》通过referer做的--》请求头中有个referer参数--》上次访问的地址
# res=requests.get('https://tupian.qqw21.com/article/UploadPic/2022-2/20222102371522350.jpg')

import requests

header = {
    'Referer': 'http://www.baidu.com'  # 从哪里访问的
}
res = requests.get('https://meizi5.com/wp-content/uploads/2024/02/VOL_181_1.jpg', headers=header)
print(res.url)
print(res.content)
with open('美女.jpg','wb') as f:
    f.write(res.content)

# with open('code.jpg', 'wb') as f:
#     for line in res.iter_content(chunk_size=1024): # 每次写入文件多大 防止数据量过大
#         f.write(line)

证书

python 复制代码
# http  和 https
	-http:超文本传输协议
    -https:安全的超文本传输协议
    -https=http+ssl/tls
    -防止:篡改,截取。。。。
    -必须有证书:才能通信

import requests
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
respone = requests.get('https://www.jianshu.com/',headers=header,verify=False)#  加上这个就不验证证书
# respone = requests.get('https://www.jianshu.com/',headers=header,cert=('/path/server.crt','/path/key'))
print(respone.text)

使用代理

python 复制代码
import requests
# 免费代理池 很少有用的 发一个请求取出一次代理
res = requests.get('http://demo.spiderpy.cn/get/?type=https')
print(res.json())
print(res.json()['proxy']) # 取出代理
# 112.30.155.83:12792

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
}
# proxies={'https': res.json()['proxy']} 使用代理获取数据 如果代理用不了 则是连接失败
response = requests.get('https://www.jianshu.com/', headers=header, proxies={'https': res.json()['proxy']})
print(response.text)

超时 异常处理 上传文件

python 复制代码
## 超时 自己设置一个时间 超过时间数据没请求会来就报错
import requests
respone=requests.get('https://www.baidu.com',timeout=1)

# 异常处理
import requests
from requests.exceptions import * #可以查看requests.exceptions获取异常类型

try:
    r=requests.get('http://www.baidu.com',timeout=0.00001)
except ReadTimeout:
    print('===:')
# except ConnectionError: #网络不通
#     print('-----')
# except Timeout:
#     print('aaaaa')

except RequestException:
    print('Error')
    
    
# 上传文件

import requests
files={'file':open('a.jpg','rb')}
respone=requests.post('http://httpbin.org/post',files=files)
print(respone.status_code)
相关推荐
小白学大数据4 小时前
Pandas与Matplotlib:Python中的动态数据可视化
开发语言·爬虫·python·pandas·matplotlib
流浪的大萝卜13 小时前
开发一个电商API接口的步骤!!!
java·大数据·前端·数据仓库·后端·爬虫·python
Bearjumpingcandy15 小时前
爬虫全网抓取
爬虫
毕设木哥15 小时前
25届计算机专业选题推荐-基于python的线上拍卖会管理系统【python-爬虫-大数据定制】
大数据·开发语言·数据库·爬虫·python·信息可视化·课程设计
全能全知者16 小时前
python简单易懂的lxml读取HTML节点及常用操作方法
开发语言·爬虫·python·html
菜鸡中的奋斗鸡→挣扎鸡17 小时前
初识爬虫3
爬虫
2401_8725149719 小时前
爬虫代理失效怎么处理?全面解决方案
网络·爬虫
布语world19 小时前
航空航司reese84逆向
爬虫·python·安全
B站计算机毕业设计超人19 小时前
计算机毕业设计Python知识图谱美团美食推荐系统 美团餐厅推荐系统 美团推荐系统 美食价格预测 美团爬虫 美食数据分析 美食可视化大屏
爬虫·python·深度学习·机器学习·数据分析·数据可视化·推荐算法