鉴于:
require 'rubygems'
require 'nokogiri'
value = Nokogiri::HTML.parse(<<-HTML_END)
"<html>
<body>
<p id='para-1'>A</p>
<div class='block' id='X1'>
<h1>Foo</h1>
<p id='para-2'>B</p>
</div>
<p id='para-3'>C</p>
<h2>Bar</h2>
<p id='para-4'>D</p>
<p id='para-5'>E</p>
<div class='block' id='X2'>
<p id='para-6'>F</p>
</div>
</body>
</html>"
HTML_END
我想做一些类似我在Hpricot中可以做的事情:
divs = value.search('//div[@id^="para-"]')
答案 0 :(得分:70)
使用xpath函数starts-with
:
value.xpath('//p[starts-with(@id, "para-")]').each { |x| puts x['id'] }
答案 1 :(得分:17)
divs = value.css('div[id^="para-"]')
答案 2 :(得分:2)
你正在寻找的一些文档:
答案 3 :(得分:1)
.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.withCredentials = true;
//rest of route code
用法:
Nokogiri::XML::Node.send(:define_method, 'xpath_regex') { |*args|
xpath = args[0]
rgxp = /\/([a-z]+)\[@([a-z\-]+)~=\/(.*?)\/\]/
xpath.gsub!(rgxp) { |s| m = s.match(rgxp); "/#{m[1]}[regex(.,'#{m[2]}','#{m[3]}')]" }
self.xpath(xpath, Class.new {
def regex node_set, attr, regex
node_set.find_all { |node| node[attr] =~ /#{regex}/ }
end
}.new)
}