【问题标题】:Selenium in Java is not finding element when using headless Chrome使用无头 Chrome 时,Java 中的 Selenium 找不到元素
【发布时间】:2020-12-16 19:19:45
【问题描述】:

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

我将此选项添加到我的 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

【问题讨论】:

  • 显然 chrome 没有制作对象。添加更多调试,n pike 是否找到任何东西......简单的顶级 levrl 元素?如果 chrome 没有创建,selenium 找不到。试试firefix看看还是低版本的chrome?
  • 是的,顶级元素。我只想从商店的产品网站上找到价格。价格稍后加载,因此不会立即显示。

标签: java selenium selenium-webdriver web-scraping webdriverwait


【解决方案1】:

在使用 模式时,您需要:

  • Maximize the browsing window

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--window-size=1400,600");
    
  • 而不是presenceOfElementLocated() 诱导WebDriverWaitvisibilityOfElementLocated() 如下:

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

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 2019-10-26
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 2022-08-14
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多