Selenium webdriver无法在chrome无头模式下定位元素

时间:2017-08-10 23:11:38

标签: java google-chrome selenium

我编写了以下脚本来练习Selenium浏览器自动化。它访问Steam的网站并更改您的Steam用户名。如果在没有Chrome无头模式的情况下运行,它可以很好地工作,但如果以{{if parent_instance.id}} <form class="nomargin" method='POST' action='' enctype='multipart/form-data'> {% csrf_token %} {{ form|crispy }} <input type='hidden' name='Parent' value='{{ parent_instance.pk }}' /> <input type='submit' value='Add a Child' class='btn btn-default' /> </form> {% endif %} 启动,则无法找到第一个元素。代码:

options.addArguments("headless")

}

崩溃时的intellij打印输出:

@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();
}

这令人困惑,因为以下代码完美无缺(从https://medium.com/@eliasnogueira/running-selenium-tests-with-chrome-headless-5edd624efb92复制粘贴)

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)

那我在这里错过了什么?我没有看到两者之间有任何严重的区别。是什么阻止我的脚本在无头模式下定位页面元素?

3 个答案:

答案 0 :(得分:0)

为了在java中使用ChromeOptions使用无头chrome,你应该使用--headless,你可能只需要替换:

options.addArguments("headless");

使用:

options.addArguments("--headless");

答案 1 :(得分:0)

尝试将屏幕尺寸更改为“ 1920x1080”,有时在屏幕尺寸不合适时确实会遇到麻烦。

答案 2 :(得分:0)

你能不能试试 belwo 设置:

options.addArguments("window-size=1400,800");
options.addArguments("headless");