2

我想抓取一个需要单击“接受条款”按钮才能进入的 javacode 呈现的网站。我正在使用 Scrapy 和 Splash,并尝试使用启动端点“render.html”和“执行”来执行 javascript 代码。在这两种情况下,输出都是起始页。为什么按预期进行这项工作?

url = 带有“接受条款”按钮的起始页。

url/index.aspx = 我要呈现的页面。

使用渲染.html:

yield scrapy.Request('url', self.parse, meta={ 'splash':
{   'endpoint':'render.html','args': {'js_source':
'document.getElementById("AcceptTerms").click();', 'html': 1, 'wait':
0.5}}})

或者通过使用执行和lua:

lua_source_string = 'function main(splash)
splash:go("url/index.aspx")
splash:wait(0.5)
splash:runjs("document.getElementById(\'AcceptTerms\').click();")
return splash:html() end'

yield scrapy.Request('url', self.parse, meta={ 'splash': { 'endpoint':'execute','args': {'lua_source' : lua_source_string}}})

'url' 是呈现的页面。

如果我按照http://blog.scrapinghub.com/2015/03/02/handling-javascript-in-scrapy-with-splash/中的示例并将以下 lua 字符串与 jquery 一起使用,如下所示:

lua_source_string = 'function main(splash)
splash:autoload("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js")
splash:go("url/index.aspx")
splash:wait(0.5)
splash:runjs("$(\'#AcceptTerms\').click();")
return splash:html() end'

或者像这样使用jquery代码:

lua_source_string = 'function main(splash)
splash:autoload("i/am/restricted/to/only/two/links/see/above/jquery.min.js")
splash:go("url/index.aspx")
splash:wait(0.5)
splash:runjs("$(\'#AcceptTerms\').trigger(\'click\');")
return splash:html() end'

我得到相同的结果。呈现的页面是“url”。

4

2 回答 2

2

我有同样的问题。我建议使用此解决方法:

function setup_casperjs(splash)  
  -- preload CasperJS client utils.  
  -- __utils__ object is compatible with CasperJS  
  splash:autoload("https://raw.githubusercontent.com/n1k0/casperjs/master/modules/clientutils.js")  
  splash:autoload([[    
    window.__utils__ = new ClientUtils({});  
  ]])
end

function main(splash)  
  setup_casperjs(splash)  
  assert(splash:go(splash.args.url))  
  assert(splash:runjs("__utils__.click('#AcceptTerms')"))  
  splash:wait(0.5)  
  return splash:html()
end

有关更详细的说明,请参阅https://github.com/scrapinghub/splash/issues/200#issuecomment-112552839 。

于 2015-08-06T11:52:46.527 回答
0

使用向执行端点发送 lua 脚本的推荐方法,

  1. splash:go 应该在 url 处加载起始页,该脚本将在该处执行,而不是在 url/index.aspx 处的目标

  2. 由于 splash:go 加载页面,因此没有必要在之后立即 splash:wait

  3. 但是,有必要在 splash:runjs 之后进行 splash:wait

  4. 通过检查 html 源代码来验证按钮的 ID。

因此,您可以将要在 splash.args 中单击的按钮的 id 传递给

function main(splash) splash:go(splash.args.url) splash:runjs('document.getElementById["'.. splash.args.submit ..'"].click();') splash:wait(0.5) return splash:html() end

于 2015-05-28T18:27:11.477 回答