我需要单击一个添加按钮,当我检查它时,我得到一个 xpath
//li[text()='Alabama']//ancestor::ul//li[2]//*[local-name()='svg']
HTML代码如下
<div class="available-state-list scroll-bar">
<ul>
<li>Alabama</li>
<li><svg width="16" height="15" viewBox="0 0 16 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3.00774 2.16391C0.246501 4.93321 0.246501 9.43934 3.00774 12.2087C5.76898 14.978 10.262 14.978 13.0232 12.2087C15.7845 9.43934 15.7845 4.93322 13.0232 2.16391C10.262 -0.605398 5.76898 -0.605398 3.00774 2.16391ZM11.0972 6.6401C11.1699 6.63823 11.2422 6.65098 11.3099 6.67759C11.3776 6.70419 11.4393 6.74413 11.4914 6.79503C11.5434 6.84593 11.5848 6.90677 11.6131 6.97397C11.6413 7.04116 11.6559 7.11335 11.6559 7.18628C11.6559 7.25921 11.6413 7.33139 11.6131 7.39859C11.5848 7.46579 11.5434 7.52663 11.4914 7.57753C11.4393 7.62843 11.3776 7.66836 11.3099 7.69497C11.2422 7.72158 11.1699 7.73433 11.0972 7.73246L8.56031 7.7327L8.56007 10.277C8.55643 10.4194 8.49746 10.5548 8.39573 10.6542C8.29399 10.7537 8.15755 10.8093 8.01548 10.8093C7.87341 10.8093 7.73697 10.7537 7.63523 10.6542C7.5335 10.5548 7.47452 10.4194 7.47089 10.277L7.47065 7.7327L4.93379 7.73246C4.79177 7.72881 4.65679 7.66967 4.55763 7.56764C4.45847 7.46561 4.40297 7.32876 4.40297 7.18628C4.40297 7.0438 4.45847 6.90695 4.55763 6.80492C4.65679 6.70289 4.79177 6.64374 4.93379 6.6401L7.47065 6.63985L7.47089 4.09559C7.47452 3.95315 7.5335 3.81778 7.63523 3.71833C7.73697 3.61888 7.87341 3.56322 8.01548 3.56322C8.15755 3.56322 8.29399 3.61888 8.39573 3.71833C8.49746 3.81778 8.55643 3.95315 8.56007 4.09559L8.56031 6.63985L11.0972 6.6401Z" fill="#1D54B4">
</path>
</svg>
</li>
</ul>
<ul>......</ul>
<ul>......</ul>
</div>
所以我尝试使用以下代码单击该 svg 元素
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
}
getElementByXpath("//li[text()='Alabama']//ancestor::ul//li[2]//*[local-name()='svg']").click();
我在提取 <svg> 元素中看到了一种使用 document.evaluate() 的解决方案?.所以在我的代码中试了一下,如下所示
document.evaluate("//li[text()='Alabama']//ancestor::ul//li[2]//svg:*[local-name()='svg']", document,
function(prefix) {
if (prefix === 'svg')
{
return 'http://www.w3.org/2000/svg';
}
else
{
return null;
}
}, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click();
但它显示错误,因为 document.evaluate(...).singleNodeValue.click 不起作用。我错了吗?任何人都可以使用 xpath 表达式帮助单击此元素吗?提前致谢。