我正试图在一个随机的facebook页面中找到所有继续阅读,并在一个新的选项卡中打开它们。
首先找到一个包含继续阅读的帖子,打开它的新选项卡,在作为新选项卡打开的页面中完成一些操作后,它将关闭,然后找到第二个持续阅读帖子,如果有,在新选项卡中打开,执行一些操作并关闭,继续处理,直到不再有连续阅读 下面的代码是我为实现上述目标而编写的。 问题由于Continue Reading元素在单击后不会消失,因此第一个元素会被连续单击并在新选项卡中打开,直到循环结束,而其他Continue Reading[/em>元素则根本不会被单击。 有没有一种方法可以解决这个问题,使所有继续阅读元素都能被找到并点击? 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
。