我编写了以下脚本来练习Selenium浏览器自动化。它访问Steam的网站并更改您的Steam用户名。如果在没有Chrome的无头模式的情况下运行,则可以完美运行,但如果以options.addArguments("headless")
开头,则无法找到第一个元素。代码:
@Test
public void steamPowered() throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Driver\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--user-data-dir=C://Users/Evan/Downloads/Profile8Aug17");
options.addArguments("headless");
options.addArguments("window-size=1200x600");
ChromeDriver driver = new ChromeDriver(options);
driver.navigate().to("https://store.steampowered.com/");
WebElement element = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("account_pulldown")));
element.click();
element = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"account_dropdown\"]/div/a[4]")));
element.click();
element = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath
("/html/body/div[1]/div[7]/div[2]/div[1]/div[1]/div/div/div/div[3]/div[2]/a/span")));
element.click();
element = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("personaName")));
element.clear();
element.sendKeys(scramble(USERNAME));
driver.findElement(By.xpath("//span[text()='Save Changes']")).click();
driver.quit();
}
}
崩溃时的IntelliJ打印输出:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate
element: {"method":"id","selector":"account_pulldown"}
(Session info: headless chrome=60.0.3112.90)
(Driver info: chromedriver=2.31.488763
(092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Windows NT 6.1.7601 SP1
x86_64) (WARNING: The server did not provide any stacktrace information)
这是令人困惑的,因为以下代码可以正常工作(从https://medium.com/@eliasnogueira/running-selenium-tests-with-chrome-headless-5edd624efb92粘贴复制)
@Test
public void testExecution() throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Driver\\chromedriver.exe");
// Add options to Google Chrome. The window-size is important for responsive sites
ChromeOptions options = new ChromeOptions();
options.addArguments("--user-data-dir=C://Users/Evan/Downloads/Profile8Aug17");
options.addArguments("headless");
options.addArguments("window-size=1200x600");
WebDriver driver = new ChromeDriver(options);
driver.get("http://seleniumhq.org");
// a guarantee that the test was really executed
assertTrue(driver.findElement(By.id("q")).isDisplayed());
driver.quit();
}
那我在这里想念什么?我看不到两者之间的任何严重差异。是什么阻止我的脚本在无头模式下查找页面元素?
最佳答案
为了在Java中使用ChromeOptions使用无头镶边,您应该使用--headless
,您可以替换为:
options.addArguments("headless");
与:
options.addArguments("--headless");