• scrapy-splash解析javascript


    所有代码均在ubuntu16.04,python3下通过

    1、不使用scrapy-splash


    比如我想爬取该人物关注了哪些贴吧,

    20180417111815667.png

    但是这些内容是javascript解析的:
    20180417111823505.png

    以在贴吧的人物主页爬取为例,在spider.py文件里面输入下面的内容。

    import scrapy
    
    
    class Spider(scrapy.Spider):
        name = 'tieba'
        allowed_domains = []
        start_urls = ["https://www.baidu.com/p/%CE%E5%D0%D0%C1%A6%D1%A7%B4%B4%CA%BC%C8%CB?from=tieba"]
    
        def start_requests(self):
            for url in self.start_urls:
                yield scrapy.Request(url=url, callback=self.parse)
    
        def parse(self,response):
            print("xxx" * 50)
            print(response.xpath('//*[@id="1000003"]/ul/li[1]/a/div[4]/text()').extract())
            print("xxx" * 50)
    

    你会看到这样的信息:
    20180417111901132.png

    2、使用scrapy-splash


    在settings.py文件中,你需要额外的填写下面的一些内容

    # 添加splash渲染服务
    SPLASH_URL = 'http://ip地址:端口号' # 这里需要填写你的ip地址
    
    # 下载器中间件
    DOWNLOADER_MIDDLEWARES = {
        'scrapy_splash.SplashCookiesMiddleware': 723,
        'scrapy_splash.SplashMiddleware': 725,
        'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
    }
    
    # 去重过滤器
    DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
    
    # 使用Splash的Http缓存
    HTTPCACHE_STOPAGE = 'scrapy_splash.SplashAwareFSCacheStorage'
    

    在spider.py文件中,填入下面的代码:

    import scrapy
    from scrapy_splash import SplashRequest # 导入scrapy_splash包
    
    
    class TiebaSpider(scrapy.Spider):
        name = 'tieba'
        allowed_domains = []
        start_urls = ["https://www.baidu.com/p/%CE%E5%D0%D0%C1%A6%D1%A7%B4%B4%CA%BC%C8%CB?from=tieba"]
    
        def start_requests(self):
            for url in self.start_urls:
                yield SplashRequest(url=url, callback=self.parse, args={'wait':1}, endpoint='render.html') # 配置requsts
    
        def parse(self, response):
            print("xxx" * 50)
            print(response.xpath('//*[@id="1000003"]/ul/li[1]/a/div[4]/text()').extract())
            print("xxx" * 50)
    

    下面就是运行这个项目,记得在docker里面先把splash渲染服务运行起来。
    结果如下图所示。
    2018041711194015.png

  • 相关阅读:
    ApacheShiro反序列化远程代码执行 漏洞处理
    js判断是电脑(pc)访问还是手机(mobile)访问
    MySQL实现主从库,AB复制配置
    js实现回到顶部功能
    JAVA结合Redis处理缓存穿透问题
    Apache Shiro使用官方自带的生成AES密钥
    JAVA将Object数组转换为String数组
    JAVA中数组(Array)、字符串(String)、集合(List、Set)相互转换
    输入npm install 报错npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! node-sass@4.13.1 postinstall: `node scripts/build.js`
    tomcat的部署jspgou+优化
  • 原文地址:https://www.cnblogs.com/selfcs/p/12611035.html
Copyright © 2020-2023  润新知