1. selenium在scrapy中的使用流程

  • 重写爬虫文件的构造方法,在该方法中使用selenium实例化一个浏览器对象(因为浏览器对象只需要被实例化一次)

  • 重写爬虫文件的closed(self,spider)方法,在其内部关闭浏览器对象。该方法是在爬虫结束时被调用

    SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
  • 重写下载中间件的process_response方法,让该方法对响应对象进行拦截,并篡改response中存储的页面数据

  • 在配置文件中开启下载中间件

2. 代码展示

- 爬虫文件:

 class WangyiSpider(RedisSpider):
     name = 'wangyi'
     #allowed_domains = ['www.xxxx.com']
     start_urls = ['https://news.163.com']
     def __init__(self):
         #实例化一个浏览器对象(实例化一次)
         self.bro = webdriver.Chrome(executable_path='/Users/bobo/Desktop/chromedriver')
 ​
     #必须在整个爬虫结束后,关闭浏览器
     def closed(self,spider):
         print('爬虫结束')
         self.bro.quit()

在Scrapy中使用Selenium 随笔 第1张在Scrapy中使用Selenium 随笔 第2张

- 中间件文件:

 from scrapy.http import HtmlResponse    
     #参数介绍:
     #拦截到响应对象(下载器传递给Spider的响应对象)
     #request:响应对象对应的请求对象
     #response:拦截到的响应对象
     #spider:爬虫文件中对应的爬虫类的实例
     def process_response(self, request, response, spider):
         #响应对象中存储页面数据的篡改
         if request.url in['http://news.163.com/domestic/','http://news.163.com/world/','http://news.163.com/air/','http://war.163.com/']:
             spider.bro.get(url=request.url)
             js = 'window.scrollTo(0,document.body.scrollHeight)'
             spider.bro.execute_script(js)
             time.sleep(2)  #一定要给与浏览器一定的缓冲加载数据的时间
             #页面数据就是包含了动态加载出来的新闻数据对应的页面数据
             page_text = spider.bro.page_source
             #篡改响应对象
             return HtmlResponse(url=spider.bro.current_url,body=page_text,encoding='utf-8',request=request)
         else:
             return response

在Scrapy中使用Selenium 随笔 第3张在Scrapy中使用Selenium 随笔 第4张

- 配置文件:

 DOWNLOADER_MIDDLEWARES = {
     'wangyiPro.middlewares.WangyiproDownloaderMiddleware': 543,
 ​
 }
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄