使用 Nokogiri 提取 HTML 中的特定节点

Extract specific nodes in HTML using Nokogiri

我想在这个 ruby 脚本中使用 Nokogiri 从 HTML 中提取一些值:

#!/usr/bin/ruby
require 'Nokogiri'

doc = Nokogiri::HTML(<<-END_OF_HTML)
  <html>
  <meta content="text/html; charset=UTF-8"/>
  <body style='margin:20px'>
    <p>The following user has registered a device, click on the link below to review the user and make any changes if necessary.</p>
    <ul style='list-style-type:none; margin:25px 15px;'>
      <li><b>User name:</b> Test User</li>
      <li><b>User email:</b> test@abc.com</li>
      <li><b>Identifier:</b> abc123def132afd1213afas</li>
      <li><b>Description:</b> Tom's iPad</li>
      <li><b>Model:</b> iPad 3</li>
      <li><b>Platform:</b> </li>
      <li><b>App:</b> Test app name</li>
      <li><b>UserID:</b> </li>
     </ul>
    <p>Review user: https://cirrus.app47.com/users?search=test@abc.com</p>            <hr style='height=2px; color:#aaa'/>
        <p>We hope you enjoy the app store experience!</p>
        <p style='font-size:18px; color:#999'>Powered by App47</p>
      <img src='https://cirrus.app47.com/notifications/562506219ac25b1033000904/img' alt=''/></body></html>
END_OF_HTML

具体来说,我想获取一些列表成员的值,例如 "Identifier:""User name:" 并将它们存储在字符串中。

我确定我需要使用 xpath 但仅此而已。我的理解是 xpath 做节点选择。

我需要用 xpath 指定什么,然后如何将选择放入一些变量中?

完整解决方案

最后我真的问了两个问题

问题 1(隐式):如何查看使用 xpath 的搜索结果?

doc.xpath("SPECIFY_SEARCH_HERE").each do |node|
puts node
end

这是可行的,因为 xpath returns 一个数组,您可以解析该数组,然后您可以对结果执行您想要的操作(在我的例子中,打印)。

问题 2:如何获取特定列表项的值?

str = doc.xpath("//ul/li[contains(b, 'Identifier')]/text()").to_s.strip

我对这一行的分析有限,但看起来是这样的:

  1. 找到 li 子键的位置://ul/li
  2. Select 包含 'Identifier'
  3. 的粗体键 (b)
  4. 从#2 中提取选择值:/text()
  5. .to_s.strip 将选择转换为字符串并删除 leading/trailing 空格

对于精通 HTML/Ruby/Xpath 的任何人,请随时更新对精度的解释。

这将 return 您要求的两个值

//ul/li[contains(b, 'Identifier') or contains(b, 'User name')]/text()

当然可以修改xpath,一次只取1个值

//ul/li[contains(b, 'Identifier')]/text()