zoukankan      html  css  js  c++  java
  • scrapy中selenium的应用

    • 重写爬虫文件的构造方法,在该方法中使用selenium实例化一个浏览器对象(因为浏览器对象只需要被实例化一次)
    • 重写爬虫文件的closed(self,spider)方法,在其内部关闭浏览器对象。该方法是在爬虫结束时被调用
    • 重写下载中间件的process_response方法,让该方法对响应对象进行拦截,并篡改response中存储的页面数据
    • 在配置文件中开启下载中间件

    4.代码展示:

    - 爬虫文件:

    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()

    - 中间件文件:

    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

    - 配置文件:

    DOWNLOADER_MIDDLEWARES = {
        'wangyiPro.middlewares.WangyiproDownloaderMiddleware': 543,
    
    }
  • 相关阅读:
    浅谈如何学好前后端
    MONGDB的使用
    一个css3特效
    axios
    css实现响应式图片及各种效果
    jQuery中.bind() .live() .delegate() .on()的区别
    HTML5 Web 存储
    HTML5中新的语义元素
    html5shiv:用于解决IE9以下版本浏览器对HTML5新增标签不识别,并导致CSS不起作用的问题
    JS移动客户端--触屏滑动事件
  • 原文地址:https://www.cnblogs.com/plyc/p/14506192.html
Copyright © 2011-2022 走看看