尝试登录 OneDrive 网页时出现 Selenium NoSuchElementException(尝试了不同的定位元素)

Selenium NoSuchElementException while trying to login to OneDrive web page (different locating elements were tried)

我打算编写一个脚本,使用 Selenium 自动登录 OneDrive 网页。 Google Chrome 和 Chromedriver Version 都是74。我总是运行 进入NoSuchElementException 并且不知道为什么。对于登录以外的其他应用程序,我在使用 Selenium 和 Chrome 设置时没有遇到任何问题。

电子邮件输入字段的 html 代码应如下所示:

<input type="email" class="form-control" aria-required="true" aria-label="E-Mail, Telefon oder Skype" placeholder="E-Mail, Telefon oder Skype" data-bind="hasFocus: focus, textInput: email, attr: {'placeholder': config.text.emailPlaceHolder,
                            'aria-label': config.text.emailPlaceHolderAria, 'aria-invalid': !error}" spellcheck="false" autocomplete="off">

代码如下所示:

from selenium import webdriver
import time

browser = webdriver.Chrome()
browser.get("https://onedrive.live.com/about/de-ch/signin/") 
time.sleep(10)

email = browser.find_element_by_xpath("/html/body/div[2]/div/main/div[2]/div[4]/div/input")
email.send_keys("test")

上面,XPath用于定位html片段,直接从Chrome复制出来。这会产生以下错误:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div/main/div[2]/div[4]/div/input"}

  (Session info: chrome=74.0.3729.131)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)

定位 html 片段的其他方法是:

username = browser.find_element_by_class_name("form-control")
username = browser.find_element_by_css_selector("input.form-control")

这些也产生了同样的错误。

根据我在网上找到的,我很确定这是正确的方法。 网页可能会阻止自动登录吗?

非常感谢您的帮助。

亲切的问候 帕斯卡

您尝试访问的元素在 iframe 中。在访问内部元素之前,您需要切换到框架。

试试这个:

wait = WebDriverWait(driver,30)
driver.get("https://onedrive.live.com/about/de-ch/signin/")

wait.until(EC.frame_to_be_available_and_switch_to_it((By.CLASS_NAME,"SignIn")))

email = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div.form-group > input.form-control")))
email.send_keys("test@etst.test")

要使用 WebDriverWait,您必须导入以下内容

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