0

我正在使用 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
4

1 回答 1

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 }
于 2013-04-10T18:06:08.727 回答