【问题标题】:Unable to select second option of radio button in selenium无法在硒中选择单选按钮的第二个选项
【发布时间】:2019-03-13 10:27:52
【问题描述】:

这是已经选择的:

<input type="radio" tabindex="0" name="accounts" onclick="populateSelection();" value="MC Credit ***388.37***" checked="">

CSS 选择器:body &gt; form &gt; span &gt; table &gt; tbody &gt; tr:nth-child(5) &gt; td.walletDispaly &gt; input[type="radio"]

xpath:/html/body/form/span/table/tbody/tr[4]/td[1]/input

这是我要选择的:

<input type="radio" tabindex="1" name="accounts" onclick="populateSelection();" value="Savings ***388.37***">

CSS 选择器:body &gt; form &gt; span &gt; table &gt; tbody &gt; tr:nth-child(7) &gt; td.walletDispaly &gt; input[type="radio"]

xpath:/html/body/form/span/table/tbody/tr[5]/td[1]/input

到目前为止我尝试了什么:

  1. driver.findElement(By.xcode("//input[@name='accounts'][2]"));
  2. driver.findElement(By.xcode("//input[@type='radio'][@name='accounts'][position()=2]"));
  3. driver.findElement(By.id("accounts"))
  4. driver.findElement(By.name("accounts"))
  5. driver.findElement(By.cssSelector("[tabindex='1']")

【问题讨论】:

  • 试试By.xpath("//input[@name='accounts' and @value='Savings']")

标签: java selenium xpath css-selectors webdriver


【解决方案1】:

为什么 xpath 不工作:

  1. //input[@name='accounts'][2]
  2. //input[@type='radio'][@name='accounts'][position()=2]

    如果你们两个元素都有兄弟关系,那么只有它有效。
    例如

    <div>
        <input type="radio" tabindex="0" name="accounts" onclick="populateSelection();" value="MC Credit ***388.37***" checked="">
       <input type="radio" tabindex="1" name="accounts" onclick="populateSelection();" value="Savings ***388.37***">
    <div>
    

    但您似乎没有这种方式的元素。

  3. driver.findElement(By.id("accounts"))

    您的元素中没有 id 属性,因此它不起作用。

  4. By.name("accounts")

  5. By.cssSelector("[tabindex='1']")

    使用相同的属性,您的页面上有多个元素,因此它正在对第一个元素执行操作,而您没有看到您想要的元素。可能是第 5 个的相同原因。

解决方案

确保您定位的元素是唯一的。您需要自定义 xpath。尝试以下解决方案:

通过.xpath

  • //input[contains(@onclick,'populateSelection')][contains( @value,'Savings')]

  • //input[@tabindex='1'][@name='accounts']

【讨论】:

    【解决方案2】:

    不要使用绝对xpath,而是使用相对xpath。对于 HTML 为:

    <input type="radio" tabindex="1" name="accounts" onclick="populateSelection();" value="Savings ***388.37***">
    

    您可以使用以下任一解决方案:

    • cssSelector:

      driver.findElement(By.cssSelector("input[name='accounts'][value^='Savings']")).click();
      
    • xpath

      driver.findElement(By.xpath("//input[@name='accounts' and starts-with(@value,'Savings')]")).click();
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2016-09-24
      • 2023-02-23
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      相关资源
      最近更新 更多