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

2024-09-30 18:19:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在刮一页,用了刮擦和飞溅。页面包含一个下拉框(技术上是一个selecthtml元素)。每次在下拉框中选择一个元素,就会使用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>

我的代码片段:

^{pr2}$

如何在程序上使用Splash“单击”并在响应对象中接收重新加载的AJAX页面?在


Tags: 元素datatitlevaluehtmlajaxbody页面
1条回答
网友
1楼 · 发布于 2024-09-30 18:19:46

您可以尝试将Splash的execute端点与LUA脚本一起使用,该脚本将用每个^{的值填充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})

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

相关问题 更多 >