无法使用 Selenium 找到元素

sha*_*azi 3 python selenium findelement

使用 Selenium,我无法在 Udemy 网站上找到“电子邮件”元素。

这是我尝试过的:

browser.get('https://www.udemy.com/join/login-popup/')
browser.implicitly_wait(5)

email = browser.find_element(By.ID, 'email--1')
print(email)
Run Code Online (Sandbox Code Playgroud)

NoSuchElementException据我所知,它给出了“email”元素甚至不在 iframe 中的情况。

那么,我怎样才能找到这个特定的元素呢?

And*_*ris 6

在这种情况下,您可能在页面加载之前查找该元素。

您应该使用 的WebDriverWait类和的Selenium条件,如下例所示:presence_of_element_locatedexpected_conditions

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait


browser.get('https://www.udemy.com/join/login-popup/')
timeout = 20  # Number of seconds before timing out.
email = WebDriverWait(browser, timeout).until(EC.presence_of_element_located((By.ID, 'email--1')))
email.send_keys("example@email.com")
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,Selenium WebDriver在抛出 a 之前最多等待 20 秒TimeoutException,除非它在上述时间内找到要返回的元素。WebDriverWait默认情况下,ExpectedCondition每 500 毫秒调用一次,直到成功返回。

最后,presence_of_element_located期望确定某个元素是否存在于页面上DOM,但不一定暗示该元素是可见的。当找到该元素时,定位器返回WebElement.