2 爬虫

 

1 搭建免费代理池

# requests模拟发送http请求,频率限制---》变换ip---》代理(免费,收费)---》
# 搭建代理池---》开源(参照:python,flask+爬虫)
通过爬虫去免费网站爬取 免费代理--》验证一下---》存到库中(redis)--->请求一个接口,就随机返回一个代理地址
 
 
 
 
 
 
#搭建步骤
 ### 第一步:下载代码
git clone git@github.com:jhao104/proxy_pool.git

 ### 第二步:安装依赖
pip3  install -r requirements.txt
   
### 第三步:修改配置--》项目路径下的settings.py
# 配置API服务
   HOST = "0.0.0.0"               # IP
   PORT = 5000                    # 监听端口
   # 配置数据库
   DB_CONN = 'redis://127.0.0.1:8888/0'
   # 配置 ProxyFetcher--->配置爬取哪几个免费代理的网站
   PROXY_FETCHER = [
       "freeProxy01",      # 这里是启用的代理抓取方法名,所有fetch方法位于fetcher/proxyFetcher.py
       "freeProxy02",
       # ....
  ]
 ### 第四步,启动项目
   # 启动调度程序(爬取代理)
   python3 proxyPool.py schedule
   # 启动webApi服务(提供接口)
   python3 proxyPool.py server
   
   
   
   
   
# 编写搭建代理池---》随机取一个值---》json格式字符串---》返回给前端

# django--->取出客户端的ip---》META:REMOTE_ADDR---》django接口,一访问就返回用户ip--》
部署在公网ip上,大家都可以访问---》使用代理测一下,看看是不是使用了代理

 


#1 使用代理池
import requests
# res=requests.get('http://127.0.0.1:5010/get/')
# print(res.json()['proxy'])
#
#
# ## 咱们的爬虫,随机使用代理去访问
# proxies={
#     'http':res.json()['proxy']
# }
# respone=requests.get('https://www.12306.cn',
#                     proxies=proxies)
#
# print(respone.status_code)

 

2 requests 超时设置,认证设置,异常处理,上传文件



### 2 超时设置
# import requests
# respone=requests.get('https://www.baidu.com',timeout=1)
# print(respone.status_code)


### 3 认证设置 --->特别古老的项目中(老版本的路由器)---》一访问,弹出输入用户名密码的框
# import requests
# from requests.auth import HTTPBasicAuth
# r=requests.get('xxx',auth=HTTPBasicAuth('user','password'))
# print(r.status_code)


### 4 异常处理
# 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('超时')
# except Exception as e:
#     print('未知错误',e)



##5 上传文件--->浏览器js上传文件,postman上传文件
# python代码上传文件---》第三方服务--》需要传文件

# 使用django写个 上传文件的后端---》前端使用requests上传试试
import requests
files={'file':open('a.txt','rb')}
respone=requests.post('http://httpbin.org/post',files=files)
print(respone.text)

 

3 爬取梨视频网站

# 爬取短视频---》https://www.pearvideo.com/--》有不同分类--》分类id号

# 打开某一个分类--->下拉会加载更多(分页)---》发送一个一个ajax请求,获取数据---》

# 下一页是向:https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=8&start=24&mrd=0.49236580390163986&filterIds=1754494,1754069,1751419,1752963,1752680,1752298,1752049,1751988,1751497,1751503,1683918,1750556,1750534,1750365,1750407----》发送get请求---》xml数据

# 向这个地址发请求,指定起始位置,每次拿12条数据


# https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=8&start=24&mrd=0.49236580390163986&filterIds=1754494,1754069,1751419,1752963,1752680,1752298,1752049,1751988,1751497,1751503,1683918,1750556,1750534,1750365,1750407


# 发送请求,获取数据

import requests
import re
res=requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=8&start=0&mrd=0.49236580390163986')
# print(res.text) # 从返回的数据中解析出视频详情地址
# 从内容中解析出所有 video_xxx--->正则
video_list=re.findall('<a href="(.*?)" class="vervideo-lilink actplay">',res.text)
# print(video_list)
for video in  video_list:
   video_id=video.split('_')[-1]
   real_video_url='https://www.pearvideo.com/'+video
   header={
       'Referer':real_video_url
  }
   res1=requests.get('https://www.pearvideo.com/videoStatus.jsp?contId=%s&mrd=0.04747965073841365'%video_id,headers=header)
   # print(res1.text)
   mp4_url=res1.json()['videoInfo']['videos']['srcUrl']
   mp4_real_url=mp4_url.replace(mp4_url.split('/')[-1].split('-')[0],'cont-%s'%video_id)
   print(mp4_real_url)
   # 向真正视频地址发请求,获取数据
   res2=requests.get(mp4_real_url)
   video_name=mp4_real_url.split('/')[-1]
   with open('video/%s'%video_name,'wb') as f:
       for line in res2.iter_content(1024):
           f.write(line)



# 视频去水印---》ffmpeg软件,python调用
# 视频裁剪----》ffmpeg软件或者自己---》打开文件-->文件操作把末尾的几个字节去掉保存起来




## 第一层反扒---》携带refer
# header={
#     'Referer':'https://www.pearvideo.com/video_1754274'
# }
# res=requests.get('https://www.pearvideo.com/videoStatus.jsp?contId=1754274&mrd=0.04747965073841365',headers=header)
# print(res.text)


## 第二层反扒-->视频地址又处理
# 能播放的地址:
# https://video.pearvideo.com/mp4/third/20220310/ cont-视频id号     -10440061-222038-hd.mp4
# https://video.pearvideo.com/mp4/third/20220310/   1647401376175   -10440061-222038-hd.mp4
# url='https://video.pearvideo.com/mp4/third/20220310/1647401376175-10440061- 222038- hd.mp4'
# url.replace(url.split('/')[-1].split('-')[1],'cont-%s'%video_id)

 

4 爬取汽车之家新闻

import requests
# 解析库 bs4
from bs4 import BeautifulSoup

res = requests.get('https://www.autohome.com.cn/news/1/#liststart')
# print(res.text)
soup = BeautifulSoup(res.text, 'lxml')
# 使用bs4,解析和获取文档中数据

# 通过bs4,找到所有类名为article的ul标签
ul_list = soup.find_all(name='ul', class_='article')
print(len(ul_list))
# 循环从ul中,找出所有的li---》一个li就是一个新闻
for ul in ul_list:
   li_list = ul.find_all(name='li')
   for li in li_list:
       title = li.find(name='h3')
       if title:  # 能找到,再继续干别的,如果没找到,说明这是个广告或者是没有标题的,不管了
           title = title.text
           url = 'http:' + li.find(name='a').attrs['href']
           desc = li.find(name='p').text
           img = 'http:'+li.find(name='img').attrs['src']
           print('''
          新闻标题:%s
          新闻地址:%s
          新闻图片:%s
          新闻摘要:%s
          ''' % (title, url, img, desc))


# 正常应该入库---》mysql,es
# 可以把图片下载到本地

 

5 beautifulsoup4 介绍

# 爬取数据没问题---》解析数据---》re---》比较好用的可以解析xml格式的库---》bs4
# 查找,修改,删除 xml文档中的标签
# pip3 install beautifulsoup4
# pip3 install lxml
from bs4 import BeautifulSoup
# lxml是使用的解析器的名字
# lxml速度快,文档容错能力强,lxml是一个第三方,需要额外安装
# 默认的html.parser :速度慢
soup=BeautifulSoup(要解析的xml字符串,'html.parser')

 

##

 

练习

搭建代理池
使用代理去爬取梨视频---》多线程
爬汽车之家数据存到mysql

 

 

 

posted @ 2022-03-16 17:50  甜甜de微笑  阅读(168)  评论(0编辑  收藏  举报