【问题标题】:selenium retrieves an error when selecting ID/XPATHselenium 在选择 ID/XPATH 时检索错误
【发布时间】:2020-02-06 17:36:41
【问题描述】:
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
from webdriver_manager.chrome import ChromeDriverManager
import chromedriver_binary
from selenium.webdriver.common.keys import Keys
import time

element = driver.find_element_by_xpath('//*[@id="username"]').send_keys(user_name)

这就是代码的样子(我尝试过 xpath、id、类名等),但我总是会出错

selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//[@id="用户名”]”} (会话信息:chrome=80.0.3987.87)

我正在尝试在 here 上完成这项工作

有什么想法吗?

【问题讨论】:

  • 你有没有写代码来打开chrome浏览器?
  • 是的 :) 浏览器打开,稍后出现错误

标签: python selenium selenium-webdriver


【解决方案1】:

我注意到给定的表单在 iframe 中,因此需要切换到 iframe 才能与 iframe 中的任何元素进行交互。

以下代码对我有用:

driver.switch_to_frame(driver.find_element_by_xpath('(//iframe[@title="Registration form"])[1]'))
element = driver.find_element_by_xpath('//*[@id="username"]').send_keys("username")

如果需要,请随意使用显式等待。

【讨论】:

  • +1 这个有效,感谢您帮助我摆脱头痛。您能否给我参考您用于构建 xpath 的文档?我用过这个selenium-python.readthedocs.io/locating-elements.html#,但你的语法似乎有点不同..
  • 另外,我注意到密码字段不在 iframe 中(并且不包含在另一个 iframe 中)所以我需要切换出框架,还是什么?当我尝试获取 xpath 的密码时,出现与用户相同的错误..
  • 对于刚开始使用 Selenium 的其他人 - 是的,您必须从 iframe/frame 切换回默认内容。使用“driver.switch_to_default_content()”
  • @Chris - 我根据自己的经验编写了 xpath,但您可以从这里了解更多信息:devhints.io/xpath,如果您完成 iframe 操作,您需要切换回默认内容.
猜你喜欢
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-22
  • 2012-03-25
  • 1970-01-01
相关资源
最近更新 更多