selenium.common.exceptions.NoSuchElementException:消息:无法找到元素:[name =“ username”]

时间:2019-08-19 17:17:22

标签: python selenium firefox

我对Python和Selenium非常陌生。我正在关注有关如何编写Instagram机器人以获得追随者和喜欢的代码的教程。

该程序将按原样打开Firefox窗口,但是当它必须填写用户名和密码字段时,它什么也不做。然后,当我关闭窗口时,我发现自己遇到了这个错误。

我收到此错误消息确实很奇怪,因为我查看了https://www.instagram.com/accounts/login/上的元素,并且在用户名字段中的密码字段中有一个名称=“用户名”和一个名称=“密码”。 / p>

有人可以帮我吗?

这是一段代码:

class InstagramBot:

def __init__(self, username, password):
    self.username = username
    self.password = password

    self.driver = webdriver.Firefox()

    self.login()

def login(self):
    self.driver.get('https://www.instagram.com/accounts/login/')

    self.driver.find_element_by_name('username').send_keys(self.username)

    self.driver.find_element_by_name('password').send_keys(self.password)

这是错误消息。

Traceback (most recent call last):
  File "C:/Users/Python Programming/PycharmProjects/insta_bot/bot.py", line 25, in <module>
    ig_bot = InstagramBot('temp_username', 'temp_password')
  File "C:/Users/Python Programming/PycharmProjects/insta_bot/bot.py", line 14, in __init__
    self.login()
  File "C:/Users/Python Programming/PycharmProjects/insta_bot/bot.py", line 19, in login
    self.driver.find_element_by_name('username').send_keys(self.username)
  File "C:\Users\Python Programming\PycharmProjects\insta_bot\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 496, in find_element_by_name
    return self.find_element(by=By.NAME, value=name)
  File "C:\Users\Python Programming\PycharmProjects\insta_bot\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\Python Programming\PycharmProjects\insta_bot\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Python Programming\PycharmProjects\insta_bot\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [name="username"]

1 个答案:

答案 0 :(得分:2)

在该元素存在之前,您可能需要等待页面上的某些脚本完成。

这是您需要的导入语句:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

使用此代码在您的send_keys行之前等待该元素:

WebDriverWait(self.driver,10).until(
         EC.presence_of_element_located((By.NAME, "username")))