我正在使用 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 页面?
最佳答案
您可以尝试将 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})
当然,这还没有经过测试,但您可以从这里开始并尝试一下。
关于python - 使用 Scrapy 和 Splash 迭代 AJAX 页面上的选定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46358240/