【发布时间】:2011-06-02 20:37:37
【问题描述】:
我正在尝试找出解析由 25 个类似这样的重复卡盘组成的搜索结果屏幕的最佳方法:
状态:活动
加入日期: 2007-08-17
地址: 123 MAIN STREET
城市: ANYTOWN 州/领地/其他: 纽约 国家/地区: 美国
邮政编码/邮政编码: 10101
我设法解析和清理页面以返回 25 个结果集之一,但我不知道如何返回其余结果集。我想实现一个从 9 增加到 33 的变量,但无法让它工作。我使用的代码如下所示:
require "nokogiri"
class String
def astrip
self.gsub(/([\x09|\x0D|\n|\t])|(\xc2\xa0){1,}/u, '').strip
end
end
i = 9
f = File.open("testpage.html", "r:iso-8859-1:utf-8")
doc = Nokogiri::HTML(f)
NAME = doc.css(":nth-child(" + i.to_s + ") div:nth-child(1) a").text.astrip.split("/")
NAME_URL = doc.css(":nth-child(" + i.to_s + ") div:nth-child(1) a").map { |link| link['href'] }
STATUS = doc.css(":nth-child(" + i.to_s + ") div:nth-child(2) a").text
JOINED = doc.css(":nth-child(" + i.to_s + ") div:nth-child(3)").text.gsub("Date Joined:", "").astrip.strip
ADDRESS1 = doc.css(":nth-child(" + i.to_s + ") div:nth-child(4)").text.gsub("Address:", "").astrip.strip
ADDRESS2 = doc.css(":nth-child(" + i.to_s + ") div:nth-child(5)").text.astrip.gsub("City:", "").gsub("State/Territory/Other", "").gsub("Country", "").split(":")
ZIPCODE = doc.css(":nth-child(" + i.to_s + ") div:nth-child(6)").text.gsub("Postal Code/Zip Code:", "").astrip.strip
Output = NAME[0].strip, NAME[1].strip, NAME_URL[0].to_s.strip, STATUS, JOINED, ADDRESS1, ADDRESS2[0].strip, ADDRESS2[1].strip, ADDRESS2[2].strip, ZIPCODE
p Output
它返回一个我很满意的输出,如下所示:
["JOHN DOE", "COMPANY NAME", "http://linktoprofile/johndoe", "ACTIVE", "2007-08-17", "123 MAIN STREET", "ANYTOWN", "NEW YORK", "US", "10101"]
【问题讨论】:
-
您的示例文本无助于确定如何访问各种标签。 Nokogiri 解析 XML 或 HTML,而不是文本,因此我们需要查看 HTML。