首页 > 解决方案 > selenium.common.exceptions.NoSuchElementException:消息:使用 Selenium Python 在 Twitter 中向电子邮件字段发送文本时无法定位元素错误

问题描述

当我尝试使用 Firefox 浏览器在 Twitter 网站上自动输入用户名和密码时出现此错误:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .session[username_or_email] 

到目前为止我写的代码集如下:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

class TwitterBot:
    def __init__(self,username,password):
        self.username = username
        self.password = password
        self.bot = webdriver.Firefox()

    def login(self):
        bot = self.bot
        bot.get('https://twitter.com/')
        time.sleep(3)
        bot.maximize_window()
        bot.implicitly_wait(3)
        email = bot.find_element_by_class_name('session[username_or_email]') 
        password = bot.find_element_by_class_name('session[password]')
        email.clear()
        password.clear()
        email.send_keys(self.username)
        password.send_keys(self.password)

run = TwitterBot('jok.moe@hotmail.com', '123456')
run.login()

有谁知道如何解决这个问题?

标签: seleniumxpathtwittercss-selectorswebdriverwait

解决方案


该元素如下所示:

<input class="js-username-field email-input js-initial-focus" type="text" name="session[username_or_email]" autocomplete="on" value="" placeholder="Phone, email or username">

因此,您可以执行以下操作:

email = bot.find_element_by_xpath('//input[@name="session[username_or_email]"]') 

推荐阅读