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的更多相关文章

  1. scrapy中间件中发送邮件

    背景介绍:之前写过通过通过scrapy的扩展发送邮件,在爬虫关闭的时候发送邮件.那个时候有个问题就是MailSender对象需要return出去.这次需要在中间件中发送邮件,但是中间件中不能随便使用r ...

  2. Scrapy中间件user-agent和ip代理使用

    一.定义实现随机User-Agent的下载中间件 1.在middlewares.py中完善代码 import random from Tencent.settings import USER_AGEN ...

  3. 在Scrapy中使用selenium

    在scrapy中使用selenium 在scrapy中需要获取动态加载的数据的时候,可以在下载中间件中使用selenium 编码步骤: 在爬虫文件中导入webdrvier类 在爬虫文件的爬虫类的构造方 ...

  4. scrapy——中间件UserAgent代理

    pip install fake-useragent 使用说明:from fake_useragent import UserAgent# 实例化一个UserAgent对象ua = UserAgent ...

  5. Scrapy中集成selenium

    面对众多动态网站比如说淘宝等,一般情况下用selenium最好 那么如何集成selenium到scrapy中呢? 因为每一次request的请求都要经过中间件,所以写在中间件中最为合适 from se ...

  6. 第三百五十一节,Python分布式爬虫打造搜索引擎Scrapy精讲—将selenium操作谷歌浏览器集成到scrapy中

    第三百五十一节,Python分布式爬虫打造搜索引擎Scrapy精讲—将selenium操作谷歌浏览器集成到scrapy中 1.爬虫文件 dispatcher.connect()信号分发器,第一个参数信 ...

  7. scrapy中的selenium

    引入 在通过scrapy框架进行某些网站数据爬取的时候,往往会碰到页面动态数据加载的情况发生,如果直接使用scrapy对其url发请求,是绝对获取不到那部分动态加载出来的数据值.但是通过观察我们会发现 ...

  8. scrapy中使用selenium来爬取页面

    scrapy中使用selenium来爬取页面 from selenium import webdriver from scrapy.http.response.html import HtmlResp ...

  9. 如何优雅的在scrapy中使用selenium —— 在scrapy中实现浏览器池

    1 使用 scrapy 做采集实在是爽,但是遇到网站反爬措施做的比较好的就让人头大了.除了硬着头皮上以外,还可以使用爬虫利器 selenium,selenium 因其良好的模拟能力成为爬虫爱(cai) ...

随机推荐

  1. 吴裕雄--天生自然 R语言开发学习:使用键盘、带分隔符的文本文件输入数据

    R可从键盘.文本文件.Microsoft Excel和Access.流行的统计软件.特殊格 式的文件.多种关系型数据库管理系统.专业数据库.网站和在线服务中导入数据. 使用键盘了.有两种常见的方式:用 ...

  2. GenerateId类:生成唯一id、订单号

    using System;using System.Security.Cryptography; namespace Infrastructure{ public class GenerateId { ...

  3. java 内存溢出-与gc

    感谢原作者 在日常中我们经常遇到这样的错误:java.lang.OutOfMemoryError: Java heap space. 但是除了heap space 的OutOfMemoryError, ...

  4. ionic2踩坑之文本域自适应高度(自定义指令,适用angular2)

    话不多说,看代码: import { Directive, ElementRef, HostListener,Input, Renderer, Component } from '@angular/c ...

  5. 转:ZABBIX监控H3C设备的CPU和内存使用率

      由于最近监控的H3C路由器经常出现死机现象,SNMP获取不到数据,后面检查发现是CPU使用率过高,直接导致无法处理SNMP请求,所以需求来了,怎样通过SNMP监控H3C路由器的CPU和内存使用率? ...

  6. 吴裕雄--天生自然KITTEN编程:逃离漩涡

  7. 红灯区:DevOps 建设的思考和实践

    点击关注"有赞coder" 获取更多技术干货哦- 作者:费解 团队:效能改进 背景 众所周知,在丰田精益生产中,核心观念包含对人的尊重.消除浪费.持续改善,只有这样,企业才能保持良 ...

  8. Fence和非原子操作的ordering

    除了在原子操作中标记memory ordering外,还可以单独使用fence指定memory ordering.Fence是全局的操作,它影响所执行线程中其他原子操作的ordering. 12345 ...

  9. 刷金币全自动脚本 | 让Python每天帮你薅一个早餐钱(送源码)

    刷金币全自动脚本 | 让Python每天帮你薅一个早餐钱(送源码) 测试开发社区  6天前 文章转载自公众号  AirPython , 作者 星安果 阅读文本大概需要 12 分钟. 1 目 标 场 景 ...

  10. Hexo next主题安装algolia

    一直在使用hexo写自己的博客,最近博客刚刚搬家重新搞了下博客: 1.为hexo添加站内搜索 我用的是algolia,在next主题5.x以上的版本集成了algolia站内搜索功能,我们只需要简单的配 ...