通过类属性的部分匹配获取所有元素
我正在尝试使用 Nokogiri 显示 URL 的结果。 (本质上是抓取一个 URL)。
我有一些类似于以下内容的 HTML:
<p class="mattFacer">Matty</p>
<p class="mattSmith">Matthew</p>
<p class="suzieSmith">Suzie</p>
所以我需要找到以“matt”一词开头的所有元素。我需要做的是保存元素的值和元素名称,以便下次可以引用它..所以我需要捕获
"Matty" and "<p class='mattFacer'>"
"Matthew" and "<p class='mattSmith'>"
我还没有弄清楚如何捕获元素 HTML,但这是我到目前为止所拥有的对于元素(它不起作用!)
doc = Nokogiri::HTML(open(url))
tmp = ""
doc.xpath("[class*=matt").each do |item|
tmp += item.text
end
@testy2 = tmp
I'm trying to use Nokogiri to display results from a URL. (essentially scraping a URL).
I have some HTML which is similar to:
<p class="mattFacer">Matty</p>
<p class="mattSmith">Matthew</p>
<p class="suzieSmith">Suzie</p>
So I need to then find all the elements which begin with the word "matt". What I need to do is save the value of the element and the element name so I can reference it next time.. so I need to capture
"Matty" and "<p class='mattFacer'>"
"Matthew" and "<p class='mattSmith'>"
I haven't worked out how to capture the element HTML, but here's what I have so far for the element (It doesnt work!)
doc = Nokogiri::HTML(open(url))
tmp = ""
doc.xpath("[class*=matt").each do |item|
tmp += item.text
end
@testy2 = tmp
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该可以帮助您开始:
This should get you started:
使用:
这会选择作为 XML 文档顶部元素的子元素且其
class
属性值以 < 开头的任何p
元素。 code>"matt" 以及任何此类p
元素的任何文本节点子节点。根据此 XML 文档进行评估时(未提供任何内容!):
选择以下节点(每个节点位于单独的行上)并且可以按位置访问:
此处是一个快速的 XSLT 验证:
当应用于同一个 XML 文档(上面)时,此转换的结果是所选节点的预期正确序列:
Use:
This selects any
p
elements that is a child of the top element of the XML document and the value of whoseclass
attribute starts with"matt"
and any text-node child of any suchp
element.When evaluated against this XML document (none was provided!):
the following nodes are selected (each on a separate line) and can be accessed by position:
Here is a quick XSLT verification:
The result of this transformation, when applied on the same XML document (above) is the expected, correct sequence of selected nodes:
接受的答案很好,但另一种方法是使用 Nikkou,它可以让您通过正则表达式进行匹配(无需熟悉 XPATH 函数):
The accepted answer is great, but another approach would be to use Nikkou, which lets you match via regular expressions (without needing to be familiar with XPATH functions):