gpt4 book ai didi

ruby-on-rails - 如果字符串以数字开头,则包含的 xpath 会抛出错误

转载 作者:太空宇宙 更新时间:2023-11-03 17:34:46 25 4
gpt4 key购买 nike

我在使用 nokogiri 和 xpath 时遇到了一个奇怪的问题。我想解析一个 HTML 文档并通过 href 值和它们包含的 anchor 文本获取所有链接。

到目前为止,这是我的 xpath:

    xpath = "//a[contains(text(), #{link['anchor_text']}) and @href='#{link['target_url']}']"
a = doc.search(xpath)

只要 link['anchor_text'] 是一个没有数字的字符串,这就可以正常工作。

如果我尝试获取带有 anchor 文本“11example”的链接,它会抛出以下错误:

    Invalid expression: //a[contains(text(), 11example) and @href='http://www.example.com/']

也许这只是一个愚蠢的错误,但我不明白为什么会出现此错误。如果我在 xpath 中的 #{link['anchor_text']} 周围加上一些引号,则没有任何效果。

编辑:这是示例 HTML:

<!DOCTYPE html>
<head>
<title>Example.com</title>
</head>
<body>
<p>
<strong>Here is some text</strong><br />
<a href="example.com" target="_blank">11example</a>Some text here and there
</p>
<p>
<strong>Another text</strong><br />
<a href="example.com/test" target="_blank">example.com</a>Some text here and there
</p>
</body>

Edit2:如果我在 irb 控制台中手动运行这些查询,一切都会按预期进行,但前提是我将文本放在引号中。

提前致谢!

亲切的问候,疯狂嬉皮士

最佳答案

简单的答案是您缺少围绕 #{link['anchor_text']} 的引号,就像你周围有 #{link['target_url']} .完整的 XPath 应该是

xpath = "//a[contains(text(), '#{link['anchor_text']}') and @href='#{link['target_url']}']"

当您不以数字开头时它似乎有效(至少不会产生错误)的原因是该字符串被解释为节点查询。例如,Nokogiri 正在寻找名为 <example.com> 的标签在<a>里面标记,然后将其转换为字符串并查看 <a> 的文本节点是否标签包含该字符串。如果标签不存在(如本例),则结果为 contains始终为真。

作为演示,使用 HTML:

<a href="example.com"><q>foo</q>example</a>
<a href="example.com"><q>foo</q>foo</a>
<a href="example.com">foo</a>

然后查询

doc.search("//a[contains(text(), q)]")

与第一个 <a> 不匹配标记,但确实匹配第二个和第三个。

当字符串以数字开头时,无法将其解析为节点查询,因为以数字开头的名称不是有效的 XML(或 HTML)元素名称,因此会出现错误。

关于ruby-on-rails - 如果字符串以数字开头,则包含的 xpath 会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20404521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com