selenium.common.exceptions.NoSuchElementException:消息:无法找到元素错误,使用Selenium Python将文本发送到Twitter中的Email字段

问题描述 投票:0回答:2

当我尝试使用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('[email protected]', '123456')
run.login()

有人知道如何解决此问题吗?

selenium xpath twitter css-selectors webdriverwait
2个回答
0
投票

该元素看起来像:

<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]"]') 

0
投票

似乎您很接近。要将字符序列发送到电子邮件密码,您必须为element_to_be_clickable()引入WebDriverWait,并且可以使用以下任何一个Locator Strategies

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.firefox.options import Options
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    class TwitterBot:
        def __init__(self,username,password):
            self.username = username
            self.password = password
            options = Options()
            options.binary_location = r'C:\Program Files\Firefox Nightly\firefox.exe'
            self.bot = webdriver.Firefox(firefox_options=options, executable_path=r'C:\WebDrivers\geckodriver.exe')
    
        def login(self):
            bot = self.bot
            bot.get('https://twitter.com/login')
            bot.maximize_window()
            WebDriverWait(bot, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.js-username-field.email-input.js-initial-focus[name='session[username_or_email]']"))).send_keys(self.username)
            bot.find_element_by_css_selector("input.js-password-field[name='session[password]']").send_keys(self.password)
    
    run = TwitterBot('[email protected]', '123456')
    run.login()
    
  • 浏览器快照:

twitter_login

© www.soinside.com 2019 - 2024. All rights reserved.