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

2024-04-26 10:04:34 发布

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

我计划编写一个脚本,使用Selenium自动登录到OneDrive网页。谷歌Chrome和Chromedriver版本都是74。我总是遇到不受欢迎的例外,不知道为什么。对于登录以外的其他应用程序,我使用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")

这些也产生了同样的错误。你知道吗

根据我在网上的发现,我确信这是正确的方法。 网页可能会阻止自动登录吗?你知道吗

非常感谢你的帮助。你知道吗

谨致问候 帕斯卡


Tags: 代码divbrowserform网页inputbyemail
1条回答
网友
1楼 · 发布于 2024-04-26 10:04:34

您试图访问的元素位于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

相关问题 更多 >