python - 在 python Scrapy 中执行 SplashRequest 时添加等待元素

标签 python scrapy wait 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",
          }
)

最佳答案

是的,您可以编写 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

在 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"
    }
}

参见脚本 tutorialreference有关如何编写 Splash Lua 脚本的更多详细信息。

关于python - 在 python Scrapy 中执行 SplashRequest 时添加等待元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41075257/

相关文章:

java - 强制执行打印顺序,但线程在一次迭代后彼此等待

python - 导入错误:无法导入名称 _aligners [biopython]

python - Maya Python,连接到 2 个列表

python - 如何使用 selenium 和 scrapy 来自动化该过程?

python - 创建Scrapy永无休止的蜘蛛

javascript - 使用scrapy抓取动态网页数据

c - wait() 在 Unix 上做什么?

python - 标识符规范化 : Why is the micro sign converted into the Greek letter mu?

python - 通过 XPath 获取文本,忽略标记

Angular 身份验证等待在守卫之前在本地存储中设置权限