Selenium Python3 - 无法按名称找到元素

Selenium Python3 - Unable to find element by its name

HTML元素的代码如下:

<input aria-label="Phone number, username, or email" aria-required="true" autocapitalize="none" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [name="username"]

当我执行这段代码时出现上面的错误:

from selenium.webdriver import Firefox

class Efrit:

    #Initializing the bot
    def __init__(self, username, password):
        self.username = username    # it could also be e-mail or phone number
        self.password = password

#Credentials to log into Instagram:
    def log(self):
        driver = Firefox('/usr/local/bin')
        driver.get("https://www.instagram.com/")
        username_location = driver.find_element_by_name('username')
        password_location = driver.find_element_by_name('password')

bot = Efrit('test, 'test')
bot.log()

您可以使用显式等待:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver.get("https://www.instagram.com/")
wait = WebDriverWait(driver, 20)
            wait.until(EC.visibility_of_element_located((SelectBy.CSS, "/input[name=username]")))
        username_location = driver.find_element_by_css_selector('input[name=username]')
        password_location = driver.find_element_by_css_selector('input[name=password]')

等待登录按钮使用element_to_be_clickable

wait.until(EC.element_to_be_clickable(
                (SelectBy.CSS_SELECTOR, ".sqdOP.L3NKy.y3zKF")))
login = driver.find_element_by_css_selector(".sqdOP.L3NKy.y3zKF")
login.click()

您还可以设置全局隐式等待。 https://selenium-python.readthedocs.io/waits.html(说明见P.5.2)

正如 JaSON 在评论中所说,登录表单不在页面源代码中,需要时间来呈现。你必须使用 wait

Explicit Wait

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

    class Efrit:
        #Initializing the bot
        def __init__(self, username, password):
            self.username = username    # it could also be e-mail or phone number
            self.password = password
    
    #Credentials to log into Instagram:
        def log(self):
            driver = Firefox('/usr/local/bin')
            driver.get("https://www.instagram.com/")
            delay = 6 # seconds
            try:
                username_location = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.NAME, 'username')))
                password_location = driver.find_element_by_name('password')
                print(username_location, password_location)
            except TimeoutException:
                print("Loading took too much time!")
            driver.quit()
    
    bot = Efrit('test', 'test')
    bot.log()