如何在Ruby中使用Nokogiri解析网页?

时间:2013-04-10 17:57:09

标签: ruby html-parsing nokogiri

我正在使用Nokogiri来解析HTML。对于显示的网站,我正在尝试创建一个哈希数组,其中每个哈希将包含网站上显示的给定评论的优缺点,缺点和建议部分。我无法做到这一点,并希望在这里提出一些建议。当我返回某个元素时,我没有在网站上显示正确的内容。有任何想法吗?

require 'open-uri'
require 'nokogiri'

# Perform a google search
doc = Nokogiri::HTML(open('http://www.glassdoor.com/Reviews/Microsoft-Reviews-E1651.htm'))

reviews = []


current_review = Hash.new

doc.css('.employerReview').each do |item|
    pro = item.parent.css('p:nth-child(1) .notranslate').text
    con = item.parent.css('p:nth-child(2) .notranslate').text
    advice = item.parent.css('p:nth-child(3) .notranslate').text

    current_review = {'pro' => pro, 'con' => con, 'advice' => advice}

    reviews << current_review
end

1 个答案:

答案 0 :(得分:1)

请改为尝试:

reviews = []
doc.css('.employerReview').each do |item|
  pro, con, advice = item.css('.description .notranslate text()').map(&:to_s)
  reviews << {'pro' => pro, 'con' => con, 'advice' => advice}
end

使用符号键也最好使用ruby,所以除非你需要它们是字符串,否则我会做

reviews << { pro: pro, con: con, advice: advice }
相关问题