它可能只是我尚未发现的代码中的一个愚蠢的错误,但它花了我很长时间:使用nokogiri和xpath解析网站,并尝试将xpaths的内容保存到。在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
我在这里错过了什么?
答案 0 :(得分:1)
不可能从你发布的内容中分辨出来,但是让我们用css清理那个热点:
kuk = searchablefile.at 'td[style*=60px]'
date = searchablefile.at 'td[style*=60px] + *'
name = searchablefile.at 'td[style*=60px] + * + *'