美文网首页
scrapy-Splash scroll to bottom 自

scrapy-Splash scroll to bottom 自

作者: 佑岷 | 来源:发表于2019-04-17 16:32 被阅读0次

    为方便集群和部署用Splash技术做动态页面爬取,效果很好,splash还可以做一些交互,网上有公司在用splash逐步替换掉selenium。当然在使用过程中也遇到一些挑战, 譬如:wait element问题、滚动翻页问题等。
    下面分享下滚动翻页问题并提供初步方案代码, 优化方案思路分享下,大家有兴趣可以写下。

    头条搜索
    https://www.toutiao.com/search/?keyword=%E5%B9%B3%E5%AE%89+%E4%BF%A1%E7%94%A8%E5%8D%A1+%E9%99%8D%E9%A2%9D

    翻页脚本:

    function main(splash)
        local num_scrolls = 10  -- 翻页数
        local scroll_delay = 0.5  -- 翻页等待时间
        local scroll_to = splash:jsfunc("window.scrollTo")
        local get_body_height = splash:jsfunc(
            "function() {return document.body.scrollHeight;}"
        )
        assert(splash:go(splash.args.url))
        splash:wait(splash.args.wait)
        for _ = 1, num_scrolls do
            scroll_to(0, get_body_height())
            splash:wait(scroll_delay)
        end 
        return {
            html = splash:html(),
            png = splash:png(),
            har = splash:har(),
        }
    end
    

    这个脚本设定了翻页次数, 其实还可以设定一直循环scroll,退出条件是:若scroll 并wait(dely time)后,检查滚动条是否仍然处于最底部, 若一直最底部可以认定已经翻到最后一页。

    相关文章

      网友评论

          本文标题:scrapy-Splash scroll to bottom 自

          本文链接:https://www.haomeiwen.com/subject/qnjnwqtx.html