ruby - 正则表达式选择id

标签 ruby regex nokogiri

当我没有确切的元素 ID,但知道一般格式时,有什么方法可以使用正则表达式或“like”函数吗?

目前我有

doc.css('table[id="UTA_basic"]//tbody')

但我想找到任何具有像 XYZ_basic 这样 id 的表,甚至任何像 _basic 这样的表都可以。

如果需要,我愿意切换到 xpath。

最佳答案

Nokogiri 支持为 CSS 和 XPath 选择器创建您自己的标签匹配器。

对于css :

Custom CSS pseudo classes may also be defined. To define custom pseudo classes, create a class and implement the custom pseudo class you want defined. The first argument to the method will be the current matching NodeSet. Any other arguments are ones that you pass in. For example:

node.css('title:regex("\w+")', Class.new {
  def regex node_set, regex
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new)

类似地,对于 xpath :

Custom XPath functions may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching NodeSet. Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example:

node.xpath('.//title[regex(., "\w+")]', Class.new {
  def regex node_set, regex
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new)

这个功能看起来可以让你深入研究标签和参数,但我还没有使用它来看看它有多大帮助。

关于doc.css('table[id="UTA_basic"]//tbody')。它看起来不像 CSS,而看起来像 XPath 表达式,将其传递给 css 会让 Nokogiri 感到困惑。另外,请确保正在解析的 HTML 实际上具有 tbody 标记。生成表格的人很少使用它们,但浏览器喜欢在解析 HTML 时将它们放入其中。在浏览器中查看 HTML 源代码将会显示它们,但通常我们不会将它们包含在任何类型的搜索中,因为在源代码中找不到它们。

关于ruby - 正则表达式选择id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919380/

相关文章:

ruby - 对 Ruby 对象进行版本控制

ruby 哈希将值从一个键交换到另一个键

ruby - 如何从哈希创建 Ruby GraphQL InputObject 实例?

regex - Perl 字符串正则表达式 - 需要解释

ruby - 如何使用 Nokogiri 选择元素

ruby - 在 Ruby 中检查 PDF 是否损坏(或只是缺少 EOF)的最快方法?

php - 用于检测链接但不检测图像的正则表达式模式

regex - 使用 RegEx 与 PowerShell 匹配

ruby - 在 View 中显示带有空格和其他符号的文件名

ruby-on-rails - 使用 Nokogiri 提取元素