使用此代码:如何在Nokogiri中使用xpath选择ID?
doc = Nokogiri::HTML(open("text.html"))
doc.xpath("//span[@id='startsWith_']").remove
我想选择每span#id
开始'startsWith_'
并将其删除。我试着搜索,但失败了。
使用此代码:如何在Nokogiri中使用xpath选择ID?
doc = Nokogiri::HTML(open("text.html"))
doc.xpath("//span[@id='startsWith_']").remove
我想选择每span#id
开始'startsWith_'
并将其删除。我试着搜索,但失败了。
试试这个XPath表达式:
//span[starts-with(@id, 'startsWith_')]
下面是一个例子:
require 'nokogiri'
html = '
<html>
<body>
<span id="doesnt_start_with">foo</span>
<span id="startsWith_bar">bar</span>
</body>
</html>'
doc = Nokogiri::HTML(html)
p doc.search('//span[starts-with(@id, "startsWith_")]').to_xml
这就是如何选择它们。
doc.search('//span[starts-with(@id, "startsWith_")]').each do |n|
n.remove
end
这就是如何删除它们。
p doc.to_xml
# >> "<span id=\"startsWith_bar\">bar</span>"
# >> "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body>\n <span id=\"doesnt_start_with\">foo</span>\n \n</body></html>\n"
页面“XPath, XQuery, and XSLT Functions”有一个可用功能列表。
你知不知道为什么某些函数不起作用(例如 - ends-with())? – taro 2011-05-14 18:51:09
我不知道,Nokogiri使用libxml2,它是一个标准的XML解析器,你应该问一下Nokogiri-谈话邮件列表。 – 2011-05-14 22:31:04
嘿,没有工作。 :^( – user647345 2011-05-12 06:52:44