【问题标题】:Xpath content not savedXpath 内容未保存
【发布时间】: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


【解决方案1】:

无法从您发布的内容中分辨出来,但让我们用 css 清理一下这个乱七八糟的东西:

kuk  = searchablefile.at 'td[style*=60px]'
date = searchablefile.at 'td[style*=60px] + *'
name = searchablefile.at 'td[style*=60px] + * + *'

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多