元素在 Selenium Chrome 无头模式下不可交互

Mub*_*Ali 9 selenium python-3.x selenium-chromedriver selenium-webdriver google-chrome-headless

当我不在无头模式下运行 chrome 时,我的代码工作得很好,但在无头模式下我得到“元素不可交互”。

我在 email_box.send_keys('') 处收到错误

我已经设置了窗口大小,但它仍然不起作用

代码:

from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import time

options = Options()
options.add_argument('headless')
options.add_argument('window-size=1366x768')

with Chrome(options=options) as driver:
    driver.get('https://accounts.google.com/login')

    WebDriverWait(driver, 20).until(lambda d: d.find_element(By.TAG_NAME, 'input'))

    time.sleep(2)
    email_box = driver.find_element(By.TAG_NAME, 'input')
    time.sleep(2)
    email_box.send_keys('example@gmail.com')
Run Code Online (Sandbox Code Playgroud)

小智 19

如果有人想要另一种解决方案,我也找到了这个。由于某种原因,当窗口未最大化时,您可能无法单击元素:

Python环境下的chromedriver中添加以下参数

from selenium.webdriver.chrome.options import Options

def get_options():
    chrome_options = Options()
    chrome_options.add_argument("--window-size=1920,1080")
    chrome_options.add_argument("--start-maximized")
    chrome_options.add_argument("--headless")
    return chrome_options
Run Code Online (Sandbox Code Playgroud)


Aru*_*han 1

要将 Gmail 发送到输入标记,请执行以下操作。

from selenium.webdriver.support import expected_conditions as EC

email_box=WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//input[@type='email']")))
driver.implicitly_wait(2)
email_box.send_keys('example@gmail.com')
Run Code Online (Sandbox Code Playgroud)