【问题标题】:How to find element by xpath that has same class, name etc如何通过 xpath 查找具有相同类、名称等的元素
【发布时间】:2021-03-17 10:18:58
【问题描述】:
有两个按钮具有相同的类、文本等。我必须找到并单击每个按钮。
<a class="jsx-1291462554"><button style="padding: 12px 15px 10px; border-radius: 4px; font: 500 15px / 16px hind; color: white; background-color: rgb(18, 83, 181); justify-content: center; text-align: center; cursor: pointer; text-decoration: none; outline: none; border: none; width: 162px;"><span class="jsx-1291462554 magzter__buttonText">Choose</span></button></a>
【问题讨论】:
标签:
java
selenium
selenium-webdriver
xpath
webdriverwait
【解决方案1】:
要启用按钮的自动点击,我们使用XPath 函数,它位于By 类中。
1.版本
driver.FindElement(By.XPath("//button[@class ='CLASS NAME']")).Click();
2.版本
driver.FindElement(By.XPath("//div[normalize-space(.)='NAME']/button")).Click();
要启用文本字段的自动输入,我们还可以使用 CssSelector 函数,它位于类 By 中。
IWebElement usernameInput = driver.FindElement(By.CssSelector("input[name='username']"));
IWebElement passwordInput = driver.FindElement(By.CssSelector("input[name='password']"));
usernameInput.SendKeys("YourUsername");
passwordInput.SendKeys("YourPassword");
【解决方案2】:
//section[contains(@class,'chooseplanTitle')]//按钮[1]
//section[contains(@class,'chooseplanTitle')]//按钮[2]
【解决方案3】:
找到与以下定位符匹配的第一个和第二个元素:
(//a[@class="jsx-1291462554"]/button)[1]
(//a[@class="jsx-1291462554"]/button)[2]
找到所有带有标签按钮的元素,并且是'a'的第一个子元素,并指定了类:
//a[@class="jsx-1291462554"]/button[1]
第一个 xpath 的 css 相等:
a.jsx-1291462554>button:nth-of-type(1)
a.jsx-1291462554>button:nth-of-type(2)
第二个 xpath 的 css 相等:
a.jsx-1291462554>button:nth-child(1)
【解决方案4】:
这两个元素都是动态元素。因此,对于第一个 Choose 上的click(),您需要为elementToBeClickable() 诱导WebDriverWait,您可以使用以下任一Locator Strategies:
-
xpath:
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//p[starts-with(., 'Choose the plan that')]//following::a[1]/button/span[text()='Choose']")));
【解决方案5】:
如果可能,放置一些东西来区分按钮的映射。但如果不可能,这些映射将解决
(//section[contains(@class, 'twocol')]/a)[1]
(//section[contains(@class, 'twocol')]/a)[2]
【解决方案6】:
List<WebElement> links = driver.findElements(By.xpath("//a[@class='jsx-1291462554']"));
links.get(0).click();
//Wait here for some action to happen
links.get(1).click();
xpath 取决于您实际想要点击的内容,如果按钮元素替换为:
//a[@class='jsx-1291462554']/button
如果按钮的单击操作更改了 DOM,您可能会遇到 StaleElementReference,在这种情况下,您可能需要在选择第二个之前再次重新获取(findElements)。