scrapy中间件中使用selenium切换ip
scrapy抓取一些需要js加载页面时一般要么是通过接口直接获取数据,要么是js加载,但是我通过selenium也可以获取动态页面
但是有个问题,容易给反爬,因为在scrapy中间件mid中使用selenium的ip不会跟着你在中间件中切换的ip变化,还是使用本机的ip在访问网站,
这里通过 确定网页url进行过滤,什么网页使用selenium,什么使用scrapy自带的抓取,
为selenium单独设置一个获取ip的办法,当然也可以使用全局变量
from selenium import webdriver
from scrapy.http.response.html import HtmlResponse
from selenium.webdriver.chrome.options import Options
import json
import requests class ip_mid(object):
def __init__(self):
self.ip = ''
self.url = 'http://proxy.1again.cc:35050/api/v1/proxy/?type=2'
self.ip_num = 0 def process_request(self,request,spider):
# if re.findall(r'根据需求的url过滤,简单的页面', request.url):
print('正在使用ip')
if self.ip_num ==0 or self.ip_num >=10:
res = json.loads(requests.get(url=self.url).content.decode())
if res:
ip = res['data']['proxy']
print(ip,'-'*20)
self.ip = ip
print(self.ip)
self.ip_num = 1 if self.ip:
request.meta['proxy'] = 'http://' + self.ip
self.ip_num += 1
print('ip地址>>>{} --- 使用次数{}'.format(self.ip, self.ip_num))
else:
self.ip_num += 3
print('使用的是本机ip......') '''
两个获取ip的设置,对ip池的访问返回是个问题,
如果加上一个判定什么网页使用selenium + 获取ip,什么网页使用正常的获取ip正常的访问
比如 if re.findall(r'根据需求的url过滤,必须使用selenium加载的js动态页面',request.url)
'''
class YanzhenIp_selenium_DownloaderMiddleware(object): def __init__(self): self.chrome_options = Options()
self.chrome_options.add_argument('--headless')
self.chrome_options.add_argument('--disable-gpu')
# self.driver = webdriver.Chrome(chrome_options=chrome_options)
self.chrome_options.add_experimental_option('excludeSwitches', ['enable-automation']) self.ip = ''
self.url = 'http://proxy.1again.cc:35050/api/v1/proxy/?type=2'
self.ip_num = 0 def process_request(self, request, spider):
# if re.findall(r'根据需求的url过滤,必须使用selenium加载的js动态页面', request.url):
print('获取ip............') # 为selenium获取ip
if self.ip_num == 0 or self.ip_num >= 3:
res = json.loads(requests.get(url=self.url).content.decode())
if res:
ip = res['data']['proxy']
self.ip = ip
self.ip_num = 1 print('调用selenium中.............') self.chrome_options.add_argument("--proxy-server=http://{}".format(self.ip)) # 加载ip
print('插入ip{},并使用{}'.format(self.ip,self.ip_num), '-' * 20)
self.driver = webdriver.Chrome(chrome_options=self.chrome_options) self.driver.get(request.url)
html = self.driver.page_source
url = self.driver.current_url response = HtmlResponse(url=url,body=html,encoding='utf-8',request=request)
return response def close_spider(self,spider):
self.driver.close()
print('关闭selenium')
ua也可以这样搞
随手一写,有待优化
ga改进版本,有待优化
class YanzhenIp_selenium_DownloaderMiddleware(object):
def __init__(self):
self.chrome_options = Options()
self.chrome_options.add_argument('--headless')
self.chrome_options.add_argument('--disable-gpu')
# self.driver = webdriver.Chrome(chrome_options=chrome_options)
self.chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
self.ip = ''
self.url = 'http://proxy.1again.cc:35050/api/v1/proxy/?type=2'
self.ip_num = 0
def process_request(self, request, spider):
# if re.findall('js加载页面的url',request.url):
if self.ip_num == 0 or self.ip_num >= 10:
res = json.loads(requests.get(url=self.url).content.decode())
if res:
ip = res['data']['proxy']
self.ip = ip
self.ip_num = 1
if re.findall('js加载页面的url', request.url):
# TODO if self.ip ?? 做个判断有咩有ip 没有的时候怎么办
print('调用selenium中.............')
self.chrome_options.add_argument("--proxy-server=http://{}".format(self.ip))
print('插入ip{},并使用{}'.format(self.ip,self.ip_num), '-' * 20)
self.driver = webdriver.Chrome(chrome_options=self.chrome_options)
self.driver.get(request.url)
html = self.driver.page_source
url = self.driver.current_url
response = HtmlResponse(url=url,body=html,encoding='utf-8',request=request)
return response
else: # 抓取简单的页面,scrapy可以胜任
if self.ip:
request.meta['proxy'] = 'http://' + self.ip
self.ip_num += 1
print('ip地址>>>{} --- 使用次数{}'.format(self.ip, self.ip_num))
else:
self.ip_num += 3
print('使用的是本机ip......')
def close_spider(self,spider):
self.driver.close()
print('关闭selenium')
scrapy中间件中使用selenium切换ip的更多相关文章
- scrapy中间件中发送邮件
背景介绍:之前写过通过通过scrapy的扩展发送邮件,在爬虫关闭的时候发送邮件.那个时候有个问题就是MailSender对象需要return出去.这次需要在中间件中发送邮件,但是中间件中不能随便使用r ...
- Scrapy中间件user-agent和ip代理使用
一.定义实现随机User-Agent的下载中间件 1.在middlewares.py中完善代码 import random from Tencent.settings import USER_AGEN ...
- 在Scrapy中使用selenium
在scrapy中使用selenium 在scrapy中需要获取动态加载的数据的时候,可以在下载中间件中使用selenium 编码步骤: 在爬虫文件中导入webdrvier类 在爬虫文件的爬虫类的构造方 ...
- scrapy——中间件UserAgent代理
pip install fake-useragent 使用说明:from fake_useragent import UserAgent# 实例化一个UserAgent对象ua = UserAgent ...
- Scrapy中集成selenium
面对众多动态网站比如说淘宝等,一般情况下用selenium最好 那么如何集成selenium到scrapy中呢? 因为每一次request的请求都要经过中间件,所以写在中间件中最为合适 from se ...
- 第三百五十一节,Python分布式爬虫打造搜索引擎Scrapy精讲—将selenium操作谷歌浏览器集成到scrapy中
第三百五十一节,Python分布式爬虫打造搜索引擎Scrapy精讲—将selenium操作谷歌浏览器集成到scrapy中 1.爬虫文件 dispatcher.connect()信号分发器,第一个参数信 ...
- scrapy中的selenium
引入 在通过scrapy框架进行某些网站数据爬取的时候,往往会碰到页面动态数据加载的情况发生,如果直接使用scrapy对其url发请求,是绝对获取不到那部分动态加载出来的数据值.但是通过观察我们会发现 ...
- scrapy中使用selenium来爬取页面
scrapy中使用selenium来爬取页面 from selenium import webdriver from scrapy.http.response.html import HtmlResp ...
- 如何优雅的在scrapy中使用selenium —— 在scrapy中实现浏览器池
1 使用 scrapy 做采集实在是爽,但是遇到网站反爬措施做的比较好的就让人头大了.除了硬着头皮上以外,还可以使用爬虫利器 selenium,selenium 因其良好的模拟能力成为爬虫爱(cai) ...
随机推荐
- 【Linux_Shell 脚本编程学习笔记五、Oracle JDK1.8 安装shell 脚本】
脚本使用说明: 首先在脚本的同级目录下有个 jdk的安装包 脚本和安装包必须在同级目录下才能够安装(脚本没有优化,还可以使用 wget 从网上下载指定版本的 jdk 安装包) #!/bin/sh ...
- 【Linux_Shell 脚本编程学习笔记三、分支与循环结构】
if 语句是实际生产工作中最重要且最常用的语句,所以,必须掌握牢固 if 条件语法 1. 单分支机构 if [ 条件 ] then 指令 fi 或 if [ 条件 ]; then 指令 fi ...
- CF-558:部分题目总结
题目链接:http://codeforces.com/contest/1163 A .Eating Soup sol:在n / 2.n - m.m三个数中取最小值,结果受这三个值限制.但是m == 0 ...
- Python 项目结构
Python 项目结构 实验准备 我们的实验项目名为 factorial. 12 $ mkdir factorial$ cd factorial/ 主代码 我们给将要创建的 Python 模块取名为 ...
- [洛谷P2613] [模板] 有理数取余
刷水题. 传送门 看似高精而非高精乃是此题最大亮点. 边读边取模技能get~ #include<cstdio> #define ll long long #define mod 19260 ...
- POJ 2728 二分+最小生成树
题意:给n个点,可以将每个点的x,y的欧几里得距离(就是坐标系里两点距离公式)看作距离,z的差值即为费用差,求的是所有最小生成树中的min(边费用和/边距离和). 思路:其实挑战P143有类似的列题, ...
- 吴裕雄--天生自然 python数据分析:基于Keras使用CNN神经网络处理手写数据集
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mp ...
- Hessian简介
Hessian Hessian是一个轻量级的remoting onhttp工具,使用简单的方法提供了RMI的功能. 相比WebService,Hessian更简单.快捷.采用的是二进制RPC协议,因为 ...
- 详解服务器性能测试的全生命周期?——从测试、结果分析到优化策略(转载)
服务器性能测试是一项非常重要而且必要的工作,本文是作者Micheal在对服务器进行性能测试的过程中不断摸索出来的一些实用策略,通过定位问题,分析原因以及解决问题,实现对服务器进行更有针对性的优化,提升 ...
- Ubuntu18.04安装Fabric
本文介绍如何在Ubuntu18.04中搭建Fabric1.4实验环境,默认使用root用户. 1.安装Golang 首先下载Golang安装包,安装包可以从这里下载.这里下载的是go1.13.4.li ...