我想选择一个HTML元素,它看起来像这样:
<button data-button-id="close" class="modal__cross modal__cross-web"></button>
现在很明显,我可以使用这个XPath选择器:
//button[(contains(@data-button-id,'close')) and (contains(@class,'modal'))]
以选择元素。但是,我确实希望选择在任何属性中都包含close
和modal
的按钮。因此,我可以概括选择器,并说:
//button[(contains(@*,'close')) and (contains(@class,'modal'))]
这是有效的。我想做的是将其扩展到以下内容:
//button[(contains(@*,'close')) and (contains(@*,'modal'))]
但这不会返回任何结果。很明显,这并不是我想要的意思。有没有正确的方法?
谢谢,Craig
看起来您使用的是XPath 1.0:在1.0中,如果您提供一个节点集作为contains()的第一个参数,则它将获取节点集中的第一个节点。属性的顺序是完全不可预测的,因此无法知道contains(@*, 'close')
是否会成功。在2.0+中,这会给您带来一个错误。
在1.0和2.0中,如果任何属性包含"0",则@*[contains(., 'close')]
返回true;关闭";作为子字符串。
此表达式有效://button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]
给定此html
<button data-button-id="close" class="modal__cross modal__cross-web"></button>
<button key="close" last="xyz_modal"></button>
使用xmllint 进行测试
echo -e 'cat //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]nbye' | xmllint --html --shell test.html
/ > cat //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]
-------
<button data-button-id="close" class="modal__cross modal__cross-web"></button>
-------
<button key="close" last="xyz_modal"></button>
/ > bye
试试这个来选择所需的元素:
//button[@*[contains(., 'close')] and @*[contains(., 'modal')]]