如何使用Selenium JavaScript和XPath点击复选框?

huangapple go评论70阅读模式
英文:

How to click on the checkbox using Selenium Javascript and Xpath?

问题

I am trying to target the checkbox to agree to the terms and conditions but have no name or id to use to target. I have innerHTML and innerText that I am trying to target with selenium but am only encountering errors. I am using Javascript and testing on chrome.

Code trial:

await driver.findElement(By.xpath("//*innerText[text()='I am at least 18 years of age and agree to the Official Rules.']")).click();

Error:

let err = new ctor(data.message)
              ^

InvalidSelectorError: invalid selector: Unable to locate an element with the xpath expression //innerText[text()='I am at least 18 years of age and agree to the Official 
Rules.'] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//innerText[text()='I am at least 18 years of age and agree to the Official Rules.']' is not a valid 
XPath expression.

Image of the checkbox:

如何使用Selenium JavaScript和XPath点击复选框?

Properties of the checkbox:

如何使用Selenium JavaScript和XPath点击复选框?

英文:

I am trying to target the checkbox to agree to the terms and conditions but have no name or id to use to target. I have innerHTML and innerText that I am trying to target with selenium but am only encountering errors. I am using Javascript and testing on chrome.

Code trial:

await driver.findElement(By.xpath("//*innerText[text()=’I am at least 18 years of age and agree to the Official Rules.’]")).click();

Error:

let err = new ctor(data.message)
              ^

InvalidSelectorError: invalid selector: Unable to locate an element with the xpath expression //innerText[text()=’I am at least 18 years of age and agree to the Official 
Rules.’] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//innerText[text()=’I am at least 18 years of age and agree to the Official Rules.’]' is not a valid 
XPath expression.

Image of the checkbox:

如何使用Selenium JavaScript和XPath点击复选框?

Properties of the checkbox:

如何使用Selenium JavaScript和XPath点击复选框?

答案1

得分: 0

所需标签是 <label> 标签。

解决方案

要点击与文本 "我至少年满18岁并同意官方规则" 相关的 [tag:checkbox],您可以使用以下 定位策略:

await driver.findElement(By.xpath("//label[@for='opt_rules']")).click();
英文:

The desired tag is a &lt;label&gt; tag.


Solution

To click on the [tag:checkbox] associated with the text "I am at least 18 years of age and agree to the Official Rules" you can use the following locator strategy:

await driver.findElement(By.xpath(&quot;//label[@for=&#39;opt_rules&#39;]&quot;)).click();

huangapple
  • 本文由 发表于 2023年6月15日 05:06:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定