解析具有动态内容的网站

时间:2013-11-12 21:55:39

标签: javascript ruby-on-rails ruby parsing nokogiri

我正在使用Nokogiri解析TechCrunch [具有特定的搜索词。

http://techcrunch.com/search/education#stq=education&stp=1

问题是网站在返回与搜索项目相关的列表之前有几秒钟的延迟,因此当Nokogiri检索到时,我输入Nokogiri解析的URL没有相关内容。

内容似乎动态加载几秒钟 - 我猜Javascript。 有关如何稍微延迟检索HTML的任何想法吗?

1 个答案:

答案 0 :(得分:3)

使用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

您可以使用this 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
相关问题