使用xpath将HTML节点解析为Ruby / Nokogiri

时间:2017-11-20 09:55:23

标签: ruby xpath nokogiri

运行以下命令,它应该返回序列。 Xpath使用chrome Xpath进行处理,但在nokogiri中它只返回空字符串。

require 'open-uri'
require 'nokogiri'

doc = Nokogiri::HTML(open("https://pt.wiktionary.org/wiki/fazer"))      

p sequence = doc.xpath('//*[@id="NavFrame1"]/div[2]/table[2]/tbody/tr[12]')

2 个答案:

答案 0 :(得分:0)

我刚刚和Capybara一起尝试过Poltergeist;它工作得很好。当我尝试使用您的代码时,div[@id="NavFrame1"]不存在。所以可能存在解析问题......

require 'capybara'
require 'capybara/dsl'
require 'capybara/poltergeist'

Capybara.register_driver :poltergeist_debug do |app|
  Capybara::Poltergeist::Driver.new(app, inspector: true)
end

Capybara.javascript_driver = :poltergeist_debug
Capybara.current_driver = :poltergeist_debug 

visit("https://pt.wiktionary.org/wiki/fazer")   
doc = Nokogiri::HTML.parse(page.html)

p sequence = doc.xpath('//*[@id="NavFrame1"]/div[2]/table[2]/tbody/tr[12]')

答案 1 :(得分:0)

问题不在于@shota

建议的解析

实际问题是您尝试解析的div元素不是第一个响应的一部分。它实际上是使用JavaScript添加的。

如果您看到

的页面来源

https://pt.wiktionary.org/wiki/fazerview-source:https://pt.wiktionary.org/wiki/fazer

您无法找到ID为 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que Frank Sinatra Fly Me To The Moon 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que Marshmello - Alone (Official Music Video) 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que [Electro] - Laszlo - Supernova [Monstercat Release 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que Louis Armstrong - What A Wonderful World [HQ] 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que Chris Brown - Turn Up the Music 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que Vangelis - Alpha 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que2 Louis Armstrong - What A Wonderful World [HQ] 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que2 [Electro] - Laszlo - Supernova [Monstercat Release 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que2 Vangelis - Alpha 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que2 Chris Brown - Turn Up the Music 12-19 21:11:34.277 14704-14704/com.sparidapps.musicplayer I/TAG: que2 Frank Sinatra Fly Me To The Moon 12-19 21:11:34.278 14704-14704/com.sparidapps.musicplayer I/TAG: que2 Marshmello - Alone (Official Music Video)

的任何元素

您还可以使用Quick Javascript switcher

之类的javascript disabler扩展来验证这一点