如何刮取延迟加载的页面

这是我用于解析网页的代码。我在rails console中做了。但是我没有在我的rails控制台中获得任何输出。我想要抓取的网站是延迟加载

require 'nokogiri' require 'open-uri' page = 1 while true url = "http://www.justdial.com/functions"+"/ajxsearch.php?national_search=0&act=pagination&city=Delhi+%2F+NCR&search=Pandits"+"&where=Delhi+Cantt&catid=1195&psearch=&prid=&page=#{page}" doc = Nokogiri::HTML(open(url)) doc = Nokogiri::HTML(doc.at_css('#ajax').text) d = doc.css(".rslwrp") d.each do |t| puts t.css(".jrcw").text puts t.css("span.jcn").text puts t.css(".jaid").text puts t.css(".estd").text page+=1 end end 

这里有2个选项:

  1. 将纯HTTP抓取切换到支持javascript评估的某些工具,例如Capybara(选择了适当的驱动程序 )。 这可能很慢,因为你在引擎盖下运行无头浏览器加上你必须设置一些超时或想出另一种方法来确保在开始任何抓取之前加载你感兴趣的文本块。

  2. 第二个选项是使用Web Developer控制台并弄清楚如何加载这些文本块(哪些AJAX调用,它们的参数等)并在您的scraper中实现它们。 这是更高级的方法,但性能更高,因为您不会做任何额外的工作,就像您在选项1中所做的那样。

祝你今天愉快!

更新:

上面的代码不起作用,因为响应是包装在JSON对象中的HTML代码,而您尝试将其解析为原始HTML。 它看起来像这样:

 { "error": 0, "msg": "request successful", "paidDocIds": "some ids here", "itemStartIndex": 20, "lastPageNum": 50, "markup": 'LOTS AND LOTS AND LOTS OF MARKUP' } 

你需要的是打开JSON,然后解析为HTML:

 require 'json' json = JSON.parse(open(url).read) # make sure you check http errors here html = json['markup'] # can this field be empty? check for the json['error'] field doc = Nokogiri::HTML(html) # parse as you like 

我还建议你不要使用open-uri因为你的代码可能会因为open-uri工作方式(阅读链接文章的详细信息)而使用动态URL而变得容易受到攻击,并使用更好的function更强大的库,例如HTTParty和RestClient 。

更新2:我的最小工作脚本:

 require 'json' require 'open-uri' require 'nokogiri' url = 'http://www.justdial.com/functions/ajxsearch.php?national_search=0&act=pagination&city=Delhi+%2F+NCR&search=Pandits&where=Delhi+Cantt&catid=1195&psearch=&prid=&page=2' json = JSON.parse(open(url).read) # make sure you check http errors here html = json['markup'] # can this field be empty? check for the json['error'] field doc = Nokogiri::HTML(html) # parse as you like puts doc.at_css('#newphoto10').attr('title') # => Dr Raaj Batra Lal Kitab Expert in East Patel Nagar, Delhi