Nig*_*y13 11 python wait scrapy scrapy-splash splash-js-render
我试图在python中使用Splash for Scrapy抓取一些动态网站.但是,我发现Splash无法等待在某些情况下加载整个页面.解决这个问题的一种强力方法是增加一个大的wait
时间(例如,在下面的代码片段中为5秒).但是,这非常低效,仍然无法加载某些数据(有时加载内容需要超过5秒).是否存在可以通过这些请求进行某种等待的元素条件?
yield SplashRequest(
url,
self.parse,
args={'wait': 5},
'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
}
)
Run Code Online (Sandbox Code Playgroud)
是的,你可以写一个Lua脚本来做到这一点.像这样的东西:
function main(splash)
splash:set_user_agent(splash.args.ua)
assert(splash:go(splash.args.url))
-- requires Splash 2.3
while not splash:select('.my-element') do
splash:wait(0.1)
end
return {html=splash:html()}
end
Run Code Online (Sandbox Code Playgroud)
在Splash 2.3之前,您可以使用splash:evaljs('!document.querySelector(".my-element")')
而不是not splash:select('.my-element')
.
将此脚本保存到变量(lua_script = """ ... """
).然后你可以发送这样的请求:
yield SplashRequest(
url,
self.parse,
endpoint='execute',
args={
'lua_source': lua_script,
'ua': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"
}
}
Run Code Online (Sandbox Code Playgroud)
有关如何编写Splash Lua脚本的更多详细信息,请参阅脚本编写教程和参考.