使用Nokogiri时出现TypeError

时间:2017-02-14 08:22:23

标签: ruby nokogiri

Nokogiri给我一页代码:

<a href="/yakutsk/search/%D0%A1%D0%BA%D0%BE%D1%80%D0%B0%D1%8F%20%D0%BC%D0%B5%D0%B4%D0%B8%D1%86%D0%B8%D0%BD%D1%81%D0%BA%D0%B0%D1%8F%20%D0%BF%D0%BE%D0%BC%D0%BE%D1%89%D1%8C/rubricId/7036994676850915/tab/firms?queryState=zoom%2F11" class="link _scheme_none rubricsList__listItemLinkTitle">Скорая медицинская помощь</a>
<a href="/yakutsk/search/%D0%A1%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D1%87%D0%BD%D0%BE-%D0%B8%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%86%D0%B8%D0%BE%D0%BD%D0%BD%D1%8B%D0%B5%20%D1%83%D1%81%D0%BB%D1%83%D0%B3%D0%B8/rubricId/7036994676850839/tab/firms?queryState=zoom%2F11" class="link _scheme_none rubricsList__listItemLinkTitle">Справочно-информационные услуги</a>
<a href="/yakutsk/search/%D0%90%D0%B2%D0%B0%D1%80%D0%B8%D0%B9%D0%BD%D1%8B%D0%B5%20%D1%81%D0%BB%D1%83%D0%B6%D0%B1%D1%8B/rubricId/7036994676850810/tab/firms?queryState=zoom%2F11" class="link _scheme_none rubricsList__listItemLinkTitle">Аварийные службы</a>
<a href="/yakutsk/search/%D0%A3%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%93%D0%9E%20%D0%B8%20%D0%A7%D0%A1/rubricId/7036994676851395/tab/firms?queryState=zoom%2F11" class="link _scheme_none rubricsList__listItemLinkTitle">Управление ГО и ЧС</a>

如您所见,只有hrefs的链接。我希望得到它的href内容。 如果我试着这样做:

data1 = data.css("li")
data2 = data1.css("a")

puts data2["href"]

我收到了一个错误:

test.rb:93:in `[]': no implicit conversion of String into Integer (TypeError)

为什么呢?当然,我可以通过简单的RegExp获得href内容。但我看到的方式很简单。

1 个答案:

答案 0 :(得分:1)

当我添加:

data2.each { |x|
      puts x["href"]
}

我得到了结果。简单。太简单。