简体   繁体   English

Python Selenium“无法定位元素”

[英]Python Selenium "Unable to locate element"

I am trying to use Selenium to sign up an email account automatically whenever I need to.我正在尝试使用 Selenium 在需要时自动注册 email 帐户。 It's just a fun learning project for me.这对我来说只是一个有趣的学习项目。 For the life of me I don't understand why it can't find the element.对于我的生活,我不明白为什么它找不到元素。 This code works fine on the sign-in page but not the sign-up page.此代码在登录页面上运行良好,但在注册页面上运行良好。 I have tried all different Selenium commands and even tried using the ID and class name.我尝试了所有不同的 Selenium 命令,甚至尝试使用 ID 和 class 名称。 Either is says it can't locate the element or that it is not reachable by keyboard.要么是说它无法找到元素,要么是键盘无法访问它。

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import time


options = Options()

driver = webdriver.Firefox(options=options, executable_path=r'geckodriver.exe')


driver.get("https://mail.protonmail.com/create/new?language=en")
time.sleep(10)
username_input = driver.find_element_by_id("username").send_keys("testusername")

Also here is the HTML code: https://i.imgur.com/ZaBMTzG.png这里还有 HTML 代码: https://i.imgur.com/ZaBMTzG.png

The username field is in iframe , you need to switch to iframe to make this work.用户名字段在iframe中,您需要切换到iframe才能使这项工作。 Below is the code that works fine:以下是可以正常工作的代码:

driver.get("https://mail.protonmail.com/create/new?language=en")
driver.switch_to.frame(driver.find_element_by_css_selector("iframe[title='Registration form'][class='top']"))
driver.find_element_by_id("username").send_keys("some string")
  1. read more about iframe here在此处阅读有关 iframe 的更多信息
  2. learn more about how to switch to iframe/frame/framset using Python selenium Bindings here在此处了解有关如何使用 Python selenium 绑定切换到 iframe/frame/frameset 的更多信息

Update:更新:

wait = WebDriverWait(driver, 30)
driver.get("https://mail.protonmail.com/create/new?language=en")
driver.switch_to.frame(driver.find_element_by_css_selector("iframe[title='Registration form'][class='top']"))
driver.find_element_by_id("username").send_keys("some string")
driver.switch_to.default_content()
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(5)
driver.switch_to.frame(driver.find_element_by_css_selector("iframe[title='Registration form'][class='bottom']"))
wait.until(EC.element_to_be_clickable((By.NAME, "submitBtn"))).click()

I'm not sure if I've seen enough code to diagnose, but I think the way you are defining username_input seems problematic.我不确定我是否看到了足够的代码来诊断,但我认为你定义username_input的方式似乎有问题。 driver.find_element_by_id("username").send_keys("testusername") doesn't actually return anything so it seems like you are setting username_input = null . driver.find_element_by_id("username").send_keys("testusername")实际上并没有返回任何内容,因此您似乎正在设置username_input = null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM