简体   繁体   中英

Name 'driver' is not defined

I'm writing a bot to access instagram, but it is giving me an error that I cannot identify.I am a beginner and I am having trouble finding the error. I am open to new friendships and to share knowledge. Thanks guys!!

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import random

class InstagramBot:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = webdriver.Firefox(executable_path=r"C:\Users\bruno\Desktop\geckodriver-v0.29.1-win64\geckodriver.exe")
           
    def login(self):
        driver = self.driver
        driver.get("https://www.instagram.com/accounts/login/?hl=pt-br")
   
    campo_usuario = driver.find_element_by_xpath("//input[@name='username']")
    campo_usuario.click()
    campo_usuario.clear()
    campo_usuario.send_keys(self.username)
    campo_senha = driver.find_element_by_xpath("//input[@name='password']")
    campo_senha.click()
    campo_senha.clear()
    campo_senha.send_keys(self.password)
    campo_senha.send_keys(Keys.RETURN)
 
   
brunoBot = InstagramBot("user","senha1234")  
brunoBot.login()

error:

 File "c:\Users\bruno\Desktop\geckodriver-v0.29.1-win64\igBot.py", line 16, in InstagramBot
    campo_usuario = driver.find_element_by_xpath("//input[@name='username']")
NameError: name 'driver' is not defined
PS C:\Users\bruno\Desktop\geckodriver-v0.29.1-win64>

You have to respect the identation for the login method:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import random

class InstagramBot:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = webdriver.Firefox(executable_path=r"C:\Users\bruno\Desktop\geckodriver-v0.29.1-win64\geckodriver.exe")
           
    def login(self):
        driver = self.driver
        driver.get("https://www.instagram.com/accounts/login/?hl=pt-br")
   
        campo_usuario = driver.find_element_by_xpath("//input[@name='username']")
        campo_usuario.click()
        campo_usuario.clear()
        campo_usuario.send_keys(self.username)
        campo_senha = driver.find_element_by_xpath("//input[@name='password']")
        campo_senha.click()
        campo_senha.clear()
        campo_senha.send_keys(self.password)
        campo_senha.send_keys(Keys.RETURN)
 
   
brunoBot = InstagramBot("user","senha1234")  
brunoBot.login()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM