我正在使用Nokogiri解析TechCrunch [具有特定的搜索词.
http://techcrunch.com/search/education#stq=education&stp=1
问题在于该站点在返回与搜索项相关的列表之前有几秒钟的延迟,因此当Nokogiri检索到它时,我输入到Nokogiri解析的URL没有相关内容.
几秒钟后,内容似乎已动态加载-我猜是Javascript.
关于如何稍微延迟检索HTML的任何想法?
解决方法:
用Ruby方法,睡觉
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。