使用无头 Chrome 时,Java 中的 Selenium 找不到元素 [英] Selenium in Java is not finding element when using headless Chrome
本文介绍了使用无头 Chrome 时,Java 中的 Selenium 找不到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从基于 JavaScript 的网站中查找一些元素.我使用 Java 和 Selenium.一切正常,但是当我想使用无头 Chrome 时,Selenium 无法找到元素.
I want to find some elements from an JavaScript based website. I use Java and Selenium. Everything works fine, but when I want to use headless Chrome, then Selenium is not able to find the elements.
我将此选项添加到我的 ChromeDriver:
I added this options to my ChromeDriver:
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$1.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
推荐答案
While using headless 模式你需要:
While using headless mode you need to:
ChromeOptions options = new ChromeOptions();
options.addArguments("--window-size=1400,600");
代替 presenceOfElementLocated()
诱导 WebDriverWait for visibilityOfElementLocated()
如下:
Instead of presenceOfElementLocated()
induce WebDriverWait for visibilityOfElementLocated()
as follows:
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[data-id='current-price']")));
这篇关于使用无头 Chrome 时,Java 中的 Selenium 找不到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文