使用Scrapy和Splash迭代AJAX页面上的选择项

时间:2017-09-22 06:31:50

标签: python web-scraping scrapy scrapy-spider scrapy-splash

我正在使用Scrapy和Splash抓取页面。该页面包含一个下拉框(从技术上讲,是一个选择HTML元素)。每次在下拉框中选择一个元素时,都会使用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“点击”并在我的响应对象中接收重新加载的AJAX页面?

1 个答案:

答案 0 :(得分:2)

您可以尝试使用具有LUA脚本的Splash的execute端点,该脚本将select填充每个option的值并返回结果。类似的东西:

...
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})

当然,这还没有经过测试,但你可以从那里开始玩它。