Search code examples
python-3.xseleniumselenium-webdrivernameerror

I'm getting a name error when running Selenium-based code


I am working on a project using the Selenium web driver. The expected output is that it should open google.com. This is the error I'm getting...

C:\Users\Admin\PycharmProjects\Rohan\venv\Scripts\python.exe 
"C:/Users/Admin/Rohan_Python/Selenium Web Driver.py"
Traceback (most recent call last):
File "C:\Users\Admin\Rohan_Python\Selenium Web Driver.py", line 8, in <module>
self.driver.get(url="https://www.google.com/")
NameError: name 'self' is not defined

My code...

    from  selenium import webdriver
    class info:
     def __init__(self):
    self.driver = webdriver.Chrome(executable_path='C:\ Users\Admin\Downloads\chromedriver_win32 
    (1)\chromedriver.exe')

  def get_info(self, query):
  self.query = query
  self.driver.get(url="https://www.google.com/")

  assist=info()
  assist.get_info("x")

Please help me and give me the solution. Thanks!


Solution

  • 1 Check indentation and blank lines. By convention you should use 4 spaces for indentation and 2 blank lines.:

    from selenium import webdriver
    
    
    class Info:
        def __init__(self):
            self.driver = webdriver.Chrome(executable_path='your path')
    

    Check here for more info on init What __init__ and self do in Python?

    For more details on indentation check here: https://www.python.org/dev/peps/pep-0008/#:~:text=The%204%2Dspace%20rule%20is%20optional%20for%20continuation%20lines.

    Next your code as well. Do not forget to indent.

    def get_info(self, query):
        self.query = query
        self.driver.get(url="https://www.google.com/")
    
    1. Class name should start from a capital letter.
    2. Start from the easiest reproducible code and after that step by step make it more complex. Here is good example for beginners https://selenium-python.readthedocs.io/getting-started.html