我有HTML代码和脚本可以根据其文本单击按钮,但是它不起作用。
简单的代码显示我的工作:
<!DOCTYPE html>
<html>
<body>
<button onclick=alert("clicked")>Try it</button>
<script>
document.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
</script>
</body>
</html>
我也使用了这个question。
答案 0 :(得分:1)
如果要按xpath查找元素,请改用document.evaluate
document.evaluate(
"//button[text()='Try it']",
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue.click()
<button onclick=alert("clicked")>Try it</button>
答案 1 :(得分:0)
作为解决方案,您可以尝试:
var searchText = "Check it";
document.querySelectorAll('button').forEach(button=>{
if(button.innerText == searchText) button.click();
});