【问题标题】:How to Select Choices input field having same class, type, Xpath everything is same如何选择具有相同类、类型、Xpath 的选项输入字段,一切都相同
【发布时间】:2018-04-20 06:46:57
【问题描述】:

我有两个输入字段来输入具有相同类别、类型的选项。 id 不同,它是动态的,并且在运行时创建,所以我不能使用 id。我使用了索引,它不能正常工作。

driver.findElement(By.xpath("//input[@type='text'][@placeholder='Provide a response entry that customers can select'][1]")).click();
driver.findElement(By.xpath("//input[@type='text'][@placeholder='Provide a response entry that customers can select'][1]")).sendKeys("Iphone 6");
driver.findElement(By.xpath("//input[@type='text'][@placeholder='Provide a response entry that customers can select'][2]")).click();
driver.findElement(By.xpath("//input[@type='text'][@placeholder='Provide a response entry that customers can select'][2]")).sendKeys("Iphone 7");

我在给定的图片链接中使用了索引。

click link to view code in organized way

索引 1 在这种情况下有效,但无法找到索引 2。

鉴于检查的 html 代码位于输入字段 1 和字段 2 的下方

字段 1 Input field 1 image Xpath link

字段 2 Input field 2 image link

【问题讨论】:

  • 请阅读为什么是screenshot of HTML or code or error is a bad idea。考虑使用基于格式化文本的相关 HTML、代码试验和错误堆栈跟踪来更新问题。
  • 用它的 id 试试。这不一样。一个是“input_168”,另一个是“input_170”。
  • 是的,我知道,但 id 是动态的,并且在运行时会发生变化,例如我第一次运行测试可能是 id 值可以是“input_168”和“input_170”。当我第二次运行测试时,它可能是“input_262”和“input_264”
  • @DebanjanB 好的,我提到了代码。首先,我认为它看起来不太可读。
  • @MuneebAkhtar 我已经缩进了您的代码试验,但为了获得有效的答案,您仍然需要提供文本格式的相关 HTML

标签: selenium testing selenium-webdriver automation automated-tests


【解决方案1】:

如果这两个input总是在这个序列中(所以第一个input总是第一,第二总是第二)

你可以使用:

driver.findElement(By.xpath("(//input[@type='text'][@placeholder='Provide a response entry that customers can select'])[1]")).click();


driver.findElement(By.xpath("(//input[@type='text'][@placeholder='Provide a response entry that customers can select'])[2]")).click();

同时我已经更正了索引中的语法

【讨论】:

    【解决方案2】:

    基于@Anand 的回答,您可以稍微简化一下:

    WebElement button1 = driver.findElement(By.xpath("(//input[@type='text' and @placeholder='Provide a response entry that customers can select'])[1]"));
    WebElement button2 = driver.findElement(By.xpath("(//input[@type='text' and @placeholder='Provide a response entry that customers can select'])[2]"));
    

    我认为使用 and 而不是堆叠括号更容易阅读。

    我同样将它用于小部件:

    WebElement header = driver.findElement(By.xpath("//div[contains(@class,'panel')]/div[contains(@class,'panel-heading') and text()[contains(.,'News Feed')]]"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多