在 Python 中尝试使用 Selenium 登录 Twitter 时无法找到电子邮件文本框的元素

Unable to locate element for email text box when trying to log in to twitter using Selenium in Python

有人可以向我解释为什么这个方法不起作用吗?

之前我在twitter登录页面用这种方式输入邮箱,是可以的。

email = bot.find_element_by_xpath(
        '//*[@id="layers"]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input'
    )
    # sends the email to the email input
    email.send_keys(self.email)
    # executes RETURN key action
    email.send_keys(Keys.RETURN)

但现在它不工作了,它 returns 这个错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="layers"]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div1/div/div[5]/label/div/div[2]/div/input"}

所以我尝试再次从twitter登录网站复制xpath如下图所示: Copy the Xpath for username text box

并对代码进行如下修改:

email = bot.find_element_by_xpath(
        '//*[@id="react-root"]/div/div/div/main/div/div/div/div[2]/div[2]/div[1]/div/div/div[5]/label/div/div[2]/div/input'
    )
    # sends the email to the email input
    email.send_keys(self.email)
    # executes RETURN key action
    email.send_keys(Keys.RETURN)

我仍然遇到相同的无法定位元素错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/div/div/div/main/div/div/div/div[2]/div[2]/div1/div/div/div[5]/label/div/div[2]/div/input"}

我仍然是使用 Selenium 的初学者,想知道为什么会发生这种情况以及解决此问题的可能方法。非常感谢您花时间阅读本文!

切勿使用浏览器 dv 工具自动创建的定位器。
正如您自己所见,它们极其脆弱且不可靠。
对于那里的用户名字段,您可以使用此定位器:

//input[@autocomplete='username']

所以你的 selenium 命令可以是

email = bot.find_element_by_xpath('//input[@autocomplete="username"]')

我建议你学习如何创建正确的定位器。
有几个关于这个的教程,例如你可以找到 here 其中一些