使用 java 运行 selenium 测试时 Headless 出现问题

Problem with Headless when running selenium test using java

我在 运行 无头模式测试时遇到问题。我用两种不同的方式(网上商店和门户)编写了我的测试用例。同样,我使用的是 Headless,当 headless 在网上商店中为真时,我的测试有效,但在门户测试用例中当 headless 为真时,它们不起作用。

org.openqa.selenium.ElementClickInterceptedException: element click intercepted: Element is not clickable at point (480, 483). Other element would receive the click: ... (Session info: headless chrome=91.0.4472.114) Build info: version: '4.0.0-beta-3', revision: '5d108f9a67' System info: host: 'moin-mkt-007.local', ip: 'fe80:0:0:0:1412:539b:3727:1402%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.6', java.version: '14.0.2' Driver info: org.openqa.selenium.chrome.ChromeDriver Command: [d05ff1a9794fef32216ef34021b22337, clickElement {id=de6be461-9b49-4e10-8d99-c008af09b8ae}] Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 91.0.4472.114, chrome: {chromedriverVersion: 91.0.4472.101 (af52a90bf870..., userDataDir: /var/folders/p9/0lhk_6lj7x7...}, goog:chromeOptions: {debuggerAddress: localhost:9222}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: MAC, platformName: MAC, proxy: Proxy(), se:cdp: ws://localhost:9222/devtool..., se:cdpVersion: 91.0.4472.114, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true} Element: [[ChromeDriver: chrome on MAC (d05ff1a9794fef32216ef34021b22337)] -> id: username] Session ID: d05ff1a9794fef32216ef34021b22337

你没有在这里展示你的代码,但我猜你在无头模式下缺少最大化屏幕。
所以我认为这样的事情应该可以解决你的问题:

opts.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200","--ignore-certificate-errors");

您需要注意几件事:

  1. 将浏览器分辨率设置为最大:

    driver.maximize_window()
    

或者如果使用 chrome 选项:

options.add_argument("--window-size=1920,1080")
  1. 利用ActionChains :

    ActionChains(driver).move_to_element(your web element here).click.perform()
    

这将是 进口 :

from selenium.webdriver.common.action_chains import ActionChains

代替your web element here你需要通过driver.find_element(By.XPATH, "some xpath")

org.openqa.selenium.ElementClickInterceptedException
It display this exception when other element obscures the desired element

try to click on the element with the WebDriverWait locator stretegy

new WebDriverWait(driver,10)
    .pollingEvery(Duration.ofMillis(10))
    .ignoring(ElementClickInterceptedException.class)
    .until(ExpectedConditions
    .elementToBeClickable(By.id("web_element")))
    .click();

As you are executing the script in the headless mode, so
options.addArguments("--headless","--disable-notifications","--window-size=1920,1080")

* this is mentioned in the other answers as well