gpt4 book ai didi

Python Selenium 不能与 WebDriverWait 一起使用

转载 作者:行者123 更新时间:2023-12-02 02:17:39 25 4
gpt4 key购买 nike

我尝试使用 Selenium 登录 Google。如果我像下面的代码一样使用 sleep() ,它就会起作用:

browser = webdriver.Firefox()
browser.get('https://admin.google.com/')

emailElem = browser.find_element_by_id('Email')
emailElem.send_keys('mymail')
nextButton = browser.find_element_by_id('next')
nextButton.click()

sleep(5)
passwordElem = browser.find_element_by_id('Passwd')
passwordElem.send_keys('mypass')
signinButton = browser.find_element_by_id('signIn')
signinButton.click()

如果我像这样将 sleep 更改为 WebDriverWait

browser = webdriver.Firefox()
browser.get('https://admin.google.com/')

emailElem = browser.find_element_by_id('Email')
emailElem.send_keys('mymail')
nextButton = browser.find_element_by_id('next')
nextButton.click()


passwordElem = WebDriverWait(browser, 5).until(
EC.presence_of_element_located(browser.find_element_by_id('Passwd'))
)
passwordElem.send_keys('mypass')
signinButton = browser.find_element_by_id('signIn')
signinButton.click()

它显示这样的错误:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="Passwd"]

如何使用 WebDriverWait?

最佳答案

是的,如Guy said ,您的 browser.find_element_by_id('Passwd')) 不是必需的。更改为((By.ID, "Passwd"))),如 the documentation 所示。代码应该是这样的:

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

browser = webdriver.Firefox()
browser.get('https://admin.google.com/')

emailElem = browser.find_element_by_id('youremail@example.com')
emailElem.send_keys('youremail')
nextButton = browser.find_element_by_id('next')
nextButton.click()


passwordElem = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.ID, "Passwd")))

passwordElem.send_keys('yourpassword')
signinButton = browser.find_element_by_id('signIn')
signinButton.click()

关于Python Selenium 不能与 WebDriverWait 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41530940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com