使用 Scrapy 和 Splash 遍历 AJAX 页面上的 select 项

Iterating through select items on AJAX page with Scrapy and Splash

我正在使用 Scrapy 和 Splash 抓取一个页面。该页面包含一个下拉框(技术上,一个 select HTML 元素)。每次在下拉框中 selected 一个元素时,使用 AJAX.

加载一个新页面

下面的 HTML 部分是我正在处理的页面的简化版本:

<html>
    <head><title>Title goes here ...</title></head>
    <body>
        <select class="foo">
            <option value=100 data-reactid=1>One</option>
            <option value=200 data-reactid=2>Two</option>
            <!-- ... -->
            <option value=900 data-reactid=9>Nine</option>
        </select>
    </body>
</html>

我的 scrapy/splash 代码片段:

# Fetch the options ... now what ?
options = response.css("select[class=foo] option[data-reactid]")

如何以编程方式使用 Splash 'click' 并在我的响应对象中接收重新加载的 AJAX 页面?

您可以尝试将 Splash 的 execute 端点与 LUA 脚本一起使用,该脚本将使用每个 option 的值和 return 填充 select结果。类似于:

...
script = """
function main(splash)
    splash.resource_timeout = 10
    splash:go(splash.args.url)
    splash:wait(1)
    splash:runjs('document.getElementsByClassName("foo")[0].value = "' .. splash.args.value .. '"')
    splash:wait(1)
    return {
        html = splash:html(),
    }
end
"""

# base_url refers to page with the select
values = response.xpath('//select[@class="foo"]/option/@value').extract()
for value in values:
    yield scrapy_splash.SplashRequest(
        base_url, self.parse_result, endpoint='execute',
        args={'lua_source': script, 'value': value, 'timeout': 3600})

当然,这还没有经过测试,但您可以从那里开始并使用它。