XPath提取问题(Ruby)

XPath提取问题(Ruby),ruby,xpath,Ruby,Xpath,最近,我发现了如何用ruby读取原始HTML,并学会了合并XPath。我试了一下,但是我犯了很多我从未见过的错误。任何知道他们在做什么的人,请帮忙 我当前的代码: require 'rexml/document' require 'open-uri' include REXML file = open("https://www.sinister.ly/Forum-Coding--71") lt = XPath(file, "//tid_60649") puts lt sleep 现代浏览器对

最近,我发现了如何用ruby读取原始HTML,并学会了合并XPath。我试了一下,但是我犯了很多我从未见过的错误。任何知道他们在做什么的人,请帮忙

我当前的代码:

require 'rexml/document'
require 'open-uri'
include REXML

file = open("https://www.sinister.ly/Forum-Coding--71")
lt = XPath(file, "//tid_60649")
puts lt
sleep

现代浏览器对于所读取的HTML非常灵活,但是像rexml这样的库就不行了。对于解析任意网站而言,Nokogiri绝对是一条出路。试试这个:

require 'nokogiri'
require 'open-uri'

url = "https://www.sinister.ly/Forum-Coding--71"
page = Nokogiri::HTML(open(url))
res = page.search("//a[@id='tid_60649']").map {|match| match.text}
p res

=> ["[Ideas?] Reading raw HTML with Ruby"]

使用除了建议使用
nokogiri
,即使您坚持使用
REXML
,您也必须正确初始化对象:
REXML::Document.new(打开(“https://www.sinister.ly/Forum-Coding--71)
。获取加载错误。猜是因为Nokogiri不是预装的宝石吗?是的,你可能必须
gem安装Nokogiri