Java 中的 Selenium 在使用 headless Chrome 时找不到元素

Selenium in Java is not finding element when using headless Chrome

我想从 Java 基于脚本的网站中找到一些元素。我使用 Java 和硒。一切正常,但是当我想使用 headless Chrome 时,Selenium 无法找到元素。

我将此选项添加到我的 Chrome驱动程序:

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");

控制台:

ChromeDriver was started successfully.
2020-08-27 22:41:46.625  INFO 20344 --- [ null to remote] o.o.selenium.remote.ProtocolHandshake    : Detected dialect: W3C
Exception in thread "Thread-8" Exception in thread "Thread-10" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for presence of element located by: By.cssSelector: [data-id='current-price'] (tried for 5 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:95)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
    at magharmi.asos.pricechecker.controller.PriceController.run(PriceController.java:52)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"[data-id='current-price']"}
  (Session info: headless chrome=85.0.4183.83)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-MMDJR4G', ip: '192.168.178.45', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '13.0.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver

使用 模式时,您需要:

  • Maximize the browsing window

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--window-size=1400,600");
    
  • 而不是 presenceOfElementLocated()visibilityOfElementLocated() 引入 ,如下所示:

    WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-id='current-price']")));