python – Splash lua脚本可以进行多次点击和访问

我正在尝试抓取
Google Scholar search results并获得与搜索匹配的每个结果的所有BiBTeX格式.现在我有一个带Splash的Scrapy爬虫.我有一个lua脚本,它将点击“Cite”链接并加载模态窗口,然后获取引文的BibTeX格式的href.但是看到有多个搜索结果,因此有多个“Cite”链接,我需要单击它们并加载各个BibTeX页面.

这就是我所拥有的:

import scrapy
from scrapy_splash import SplashRequest


class CiteSpider(scrapy.Spider):
    name = "cite"
    allowed_domains = ["scholar.google.com", "scholar.google.ae"]
    start_urls = [
        'https://scholar.google.ae/scholar?q="thermodynamics"&hl=en'
    ]

    script = """
        function main(splash)
          local url = splash.args.url
          assert(splash:go(url))
          assert(splash:wait(0.5))
          splash:runjs('document.querySelectorAll("a.gs_nph[aria-controls=gs_cit]")[0].click()')
          splash:wait(3)
          local href = splash:evaljs('document.querySelectorAll(".gs_citi")[0].href')
          assert(splash:go(href))
          return {
            html = splash:html(),
            png = splash:png(),
            href=href,
          }
        end
        """

    def parse(self, response):
        yield SplashRequest(self.start_urls[0], self.parse_bib,
                            endpoint="execute",
                            args={"lua_source": self.script})

    def parse_bib(self, response):
        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.css("body > pre::text").extract()[0])

我想我应该在执行querySelectorAll调用时将“Cite”链接的索引传递给lua脚本,但我似乎无法找到将另一个变量传递给函数的方法.另外我假设我必须做一些脏的javascript history.back()在获得BibTeX之后返回到原始结果页面,但我觉得有更优雅的方式来处理这个问题.

最佳答案 好的,所以我破解了一个有效的解决方案.首先,我们需要Lua脚本是可变的,所以我们将它变成一个函数:

def script(n):
    _script = """
        function main(splash)
          local url = splash.args.url
          local href = ""
          assert(splash:go(url))
          assert(splash:wait(0.5))
          splash:runjs('document.querySelectorAll("a.gs_nph[aria-controls=gs_cit]")[{}].click()')
          splash:wait(3)
          href = splash:evaljs('document.querySelectorAll("a.gs_citi")[0].href')
          assert(splash:go(href))
          return {}
        end
        """.format(n, "{html=splash:html(),png=splash:png(), href=href,}")
    return _script

然后,我必须修改解析函数,以便它单击页面上的所有“引用”链接.这样做的方法是遍历页面上所有匹配的“引用”链接,并单独单击每个链接.我让Lua脚本再次加载页面(这是脏的,但我想不出任何其他方式)并单击查询的“Cite”链接的索引.此外,它必须发出重复请求,因此dont_filter = True存在的原因是:

def parse(self, response):
        n = len(response.css("a.gs_nph[aria-controls=gs_cit]").extract())
        for i in range(n):
            yield SplashRequest(response.url, self.parse_bib,
                                endpoint="execute",
                                args={"lua_source": script(i)},
                                dont_filter=True)

希望这可以帮助.

点赞