我正在使用Nokogiri解析TechCrunch [具有特定的搜索词。
http://techcrunch.com/search/education#stq=education&stp=1
问题在于该站点在返回与搜索项相关的列表之前有几秒钟的延迟,因此当Nokogiri检索到它时,我输入到Nokogiri进行解析的URL没有相关内容。
几秒钟后,内容似乎已动态加载-我猜是Javascript。关于如何稍微延迟检索HTML的任何想法?
使用Ruby方法, sleep
seconds_to_delay = 5
sleep seconds_to_delay
编辑1:处理在文档完成加载后加载一段时间的div
我讨厌这种情况。我必须处理完全相同的情况,所以这就是我的解决方法。您需要使用类似selenium-webdriver gem的工具。
require 'selenium-webdriver'
url = "http://techcrunch.com/search/education#stq=education&stp=1"
css_selector = ".tab-panel.active"
driver = Selenium::WebDriver.for :firefox
driver.get(url)
driver.switch_to.default_content
posts_text = driver.find_element(:css, css_selector).text
puts posts_text
driver.quit
如果您在Heroku,AWS EC2或Digital Ocean之类的虚拟机上运行此程序,则不能使用firefox。相反,您需要像phantom.js这样的无头浏览器。
为了使用phantom.js而不是firefox,首先,在VM上安装phantomjs。然后更改为driver = Selenium::WebDriver.for :phantomjs
。
您可以使用此gem实际为您安装phantomjs。
问题b)的第二次编辑
require 'selenium-webdriver'
url = "http://techcrunch.com/search/education#stq=education&stp=1"
css_selector = ".tab-panel.active ul.river-compact.river-search li"
driver = Selenium::WebDriver.for :phantomjs
driver.get(url)
driver.switch_to.default_content
items = driver.find_elements(:css, css_selector)
items.each {|x| puts x }
driver.quit
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句