[英]How to find multiple different Webelements with Selenium that have the same attribute?
[英]Find and click on all the webelements with same locator
我试图在随机的Facebook页面中找到所有的“ 继续阅读” ,然后在新标签页中打开它们。
首先找到包含继续阅读的帖子,打开新标签,在作为新标签打开的页面中完成某些操作后,它将关闭,然后找到第二个继续阅读的帖子(如果有的话),在新标签中打开,进行一些操作并关闭,继续操作,直到没有更多的继续阅读帖子。
下面的代码是我为实现上述目的而编写的代码。
List <WebElement> continuereading = driver.findElements(By.xpath("//span[@class='text_exposed_link']//a[@target='_blank' and contains (text(), 'Continue Reading')]"));
System.out.println(continuereading);
for (int i=0; i <= continuereading.size(); i++){
//check if there is continue reading element in post
if (continuereading.size() > 0) {
WebElement contreading = driver.findElement(By.xpath("//span[@class='text_exposed_link']//a[@target='_blank' and contains (text(), 'Continue Reading')]"));
//open link in new tab
Actions action = new Actions(driver);
action.keyDown(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform();
//scroll to the element
jse.executeScript("arguments[0].scrollIntoView(true);", contreading);
contreading.click();
action.keyUp(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform();
//close new tab
action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0077')).perform();
action.keyUp(Keys.CONTROL).sendKeys(String.valueOf('\u0077')).perform();
}
}
问题由于单击后继续阅读元素不会消失,因此第一个元素会被连续单击并在新选项卡中打开,直到循环结束,而其他继续阅读元素将根本不会被单击。
有没有一种方法可以解决此问题,从而可以找到并单击所有“ 继续阅读”元素?
那是因为在您的for
循环中,您再次得到了元素。
WebElement contreading = driver.findElement(By.xpath("//span[@class='text_exposed_link']//a[@target='_blank' and contains (text(), 'Continue Reading')]"));
此特定行将始终为您提供页面上的第一个元素,然后单击它(正是您所遇到的)。 相反,只需执行以下操作:
for (int i=0; i < continuereading.size(); i++){
//open link in new tab
Actions action = new Actions(driver);
action.keyDown(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform();
//scroll to the element
jse.executeScript("arguments[0].scrollIntoView(true);", continuereading.get(i));
continuereading.get(i).click();
action.keyUp(Keys.LEFT_CONTROL).keyDown(Keys.LEFT_SHIFT).perform();
//close new tab
action.keyDown(Keys.CONTROL).sendKeys(String.valueOf('\u0077')).perform();
action.keyUp(Keys.CONTROL).sendKeys(String.valueOf('\u0077')).perform();
}
请注意,我还修复了您的for
循环迭代。 您从0
迭代到包含的list.size()
,最终将抛出和IndexOutOfBoundsException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.