【问题标题】:I'm getting a name error when running Selenium-based code运行基于 Selenium 的代码时出现名称错误
【发布时间】:2021-04-13 09:11:51
【问题描述】:

我正在使用 Selenium Web 驱动程序开发一个项目。预期的输出是它应该打开 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")

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

【问题讨论】:

  • 看起来你的缩进有问题

标签: python-3.x selenium selenium-webdriver nameerror


【解决方案1】:

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. 类名应以大写字母开头。
  2. 从最简单的可重现代码开始,然后逐步使其变得更复杂。这是初学者的好例子https://selenium-python.readthedocs.io/getting-started.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多