为什么即使元素存在,硒抛出元素也找不到错误?

时间:2020-11-08 08:46:15

标签: python selenium selenium-chromedriver

这是我写的,它是一个用于登录我的instagram帐户的简单程序,凭据已更改:

from selenium import webdriver
import time
import os

class InstaBot:

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

        self.username = username
        self.password = password

        self.driver = webdriver.Chrome('./chromedriver.exe')

        self.login()

    def login(self):

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

        # login_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/div[3]') # login button xpath changes after text is entered, find first

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

        # login_btn.click()

if __name__ == '__main__':

    ig_bot = InstaBot(username='temp', password='tempp')

我不知道为什么会引发错误。请帮忙。

Traceback (most recent call last):
  File "instabot.py", line 30, in <module>
    ig_bot = InstaBot(username='temp', password='tempp')
  File "instabot.py", line 15, in __init__
    self.login()
  File "instabot.py", line 23, in login
    self.driver.find_element_by_name('username').send_keys(self.username)
  File "C:\Program Files\Python37\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:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="username"]"}
  (Session info: chrome=86.0.4240.183)

Chrome确实打开了登录页面,但是找不到该元素。

PS:您可能已经猜到我是新手

编辑:

我发现当我使用time.sleep几秒钟时,它可以正常工作...。 但是我不认为它是修复它的最佳方法,因此请注意并向我提出建议,或者这实际上是它的工作原理...

1 个答案:

答案 0 :(得分:-1)

我找到答案了,是的!

在搜索元素之前,我应该等待页面加载,它们有两种类型:

1次明确等待

2次隐式等待

这些实际上记录在这里:https://selenium-python.readthedocs.io/waits.html

在搜索元素之前,应添加以下内容:

WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, "Sign up")))

要执行此操作,顶部需要一些导入行,即

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

编辑1: 我以前使用的是隐式的,现在使用的是显式的