使用Selenium Java在网页上按多个选项卡

时间:2018-08-27 19:34:47

标签: java selenium selenium-webdriver

我试图通过按Tab键单击一个Web元素,要查找此元素,我需要按Tab键15次。我有这段代码可以按Tab键并输入:

driver.switchTo().activeElement().sendKeys(Keys.TAB);
driver.switchTo().activeElement().sendKeys(Keys.ENTER);

我在互联网上搜索,然后使用Python找到了以下代码:

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

N = 5  # number of times you want to press TAB

actions = ActionChains(browser) 
for _ in range(N):
actions = actions.send_keys(Keys.TAB)
actions.perform()

或者,因为这是Python,您甚至可以执行以下操作:

actions = ActionChains(browser) 
actions.send_keys(Keys.TAB * N)
actions.perform()

可以使用Java帮助我吗?谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用多种方法执行此操作。在这里我使用while循环:

import org.openqa.selenium.Keys;
import org.openqa.selenium.interactions.Actions;
int x = 1;
// Exit when x becomes greater than 15
while (x<=15){
  driver.findElement("your locator here").sendKeys(Keys.TAB);
  // Increment the value of x for
  // next iteration
  x++;
}

答案 1 :(得分:0)

您可以这样做:

Actions actions = new Actions(driver);
for (int i = 0; i < 15; i++) {
    actions.sendKeys(Keys.TAB).build().perform();
}
actions.sendKeys(Keys.ENTER).build().perform();

您还可以找到最接近焦点的元素(例如输入,按钮..),并使用较少的标签转到目标元素:

Actions actions = new Actions(driver);

((JavascriptExecutor)driver).executeScript("arguments[0].focus()", driver.findElement(closestElementLocator));
for (int i = 0; i < 2; i++) {
   actions.sendKeys(Keys.TAB).build().perform();
}
actions.sendKeys(Keys.ENTER).build().perform();

//You can also get the element
//WebElement targetElement = driver.switchTo().activeElement();
//targetElement.sendKeys(Keys.ENTER);