Chrome驱动程序无法在无头模式打开时检测gmail上的电子邮件字段

2024-09-28 01:27:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用SeleniumWebDriver登录gmail

以下代码在没有headless选项的情况下工作,我可以成功登录:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
options.add_argument(" — incognito")
loadtime = 4.0

try:
    browser = webdriver.Chrome(chrome_options=options)
except:
    browser = webdriver.Chrome('./chromedriver', chrome_options=options)

gmail_link = 'https://accounts.google.com/signin'

browser.get(gmail_link)

email = WebDriverWait(browser, loadtime).until(EC.visibility_of_element_located((By.ID, "identifierId")))
email.send_keys('my_email')
nextButton = WebDriverWait(browser, loadtime).until(lambda x: x.find_element_by_id('identifierNext'))
nextButton.click()

password = WebDriverWait(browser, loadtime).until(
    EC.element_to_be_clickable((By.XPATH, "//input[@name='password']"))
)
password.send_keys('my_password')
browser.find_element_by_id("passwordNext").click()

但如果我添加以下选项,它就无法找到email元素并超时

options.add_argument('--headless')

在您将此问题标记为重复问题之前(我知道还有许多其他类似问题,但没有一个对我有帮助):

我想提到的是,这对其他网站有效,例如,我可以去facebook并使用headless选项登录。但出于某种原因,gmail的无头选项似乎看不到电子邮件字段

因此,这个问题感觉像是gmail特有的

这是检查gmail上的电子邮件字段时的样子: enter image description here

关于如何克服这个问题有什么想法吗


Tags: fromimportbrowseremail选项seleniumpasswordelement
2条回答

我建议在无头模式下运行测试时获取页面源代码。这是可能的,在无头结构可以是不同的。 此外,请尝试使用不同的定位器,例如//input[@type='email']-首先确保没有其他类型为'email'的输入

这是因为在无头模式下,chrome会选择gmail的最旧版本或不支持JS的版本。如果您转到站点设置并禁用gmail的javascript,那么您将在重新访问时获得另一个版本的gmail。因此,chrome在无头模式下运行时使用了旧版本的xpath如果你想在gmail中运行selenium,你可以选择mozilla,它工作正常,或者在chrome无头模式下运行时为浏览器提供用户代理

相关问题 更多 >

    热门问题