运行 基于 Selenium 的代码时出现名称错误

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

我正在开发一个使用 Selenium 网络驱动程序的项目。预期的输出是它应该打开 google.com。 这是我遇到的错误...

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

我的代码...

    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")

请帮助我并给我解决方案。谢谢!

1 检查缩进和空行。按照惯例,您应该使用 4 个空格进行缩进和 2 个空行。:

from selenium import webdriver


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

在此处查看有关 init What __init__ and self do in Python?

的更多信息

有关缩进的更多详细信息,请在此处查看:https://www.python.org/dev/peps/pep-0008/#:~:text=The%204%2Dspace%20rule%20is%20optional%20for%20continuation%20lines

接下来是你的代码。不要忘记缩进。

def get_info(self, query):
    self.query = query
    self.driver.get(url="https://www.google.com/")
  1. Class 名称应以大写字母开头。
  2. 从最简单的可重现代码开始,然后逐步使其变得更复杂。这是初学者的好例子https://selenium-python.readthedocs.io/getting-started.html