【发布时间】:2012-11-13 10:51:50
【问题描述】:
这可能只是我还没有发现的代码中的一个愚蠢的错误,但这花了我相当长的时间:使用 nokogiri 和 xpath 解析网站,并尝试将 xpath 的内容保存到 . csv 文件,csv 文件有空单元格。
基本上,xpath 的内容返回空或者我的代码没有正确读取网站。
这就是我正在做的:
require 'open-uri'
require 'nokogiri'
require 'csv'
CSV.open("neverend.csv", "w") do |csv|
csv << ["kuk","date","name"]
#first, open the urls from a document. The urls are correct.
File.foreach("neverendurls.txt") do |line|
#second, the loop for each url
searchablefile = Nokogiri::HTML(open(line))
#third, the xpaths. These work when I try them on the website.
kuk = searchablefile.at_xpath("(//tbody/tr/td[contains(@style,'60px')])[1]")
date = searchablefile.at_xpath("(//tbody/tr/td[contains(@style,'60px')])[1]/following-sibling::*[1]")
name = searchablefile.at_xpath("(//tbody/tr/td[contains(@style, '60px')])[1]/following-sibling::*[2]")
#fourth, saving the xpaths
csv << [kuk,date,name]
end
end
我在这里错过了什么?
【问题讨论】:
-
我想我有答案.. (1) 不要相信浏览器中的 xpath 检查。 (2) 注意,不要使用!
标签: ruby xpath nokogiri scraper