简体   繁体   English

Python Selenium “名称‘驱动程序’未定义”

[英]Python Selenium “name 'driver' is not defined”

I'm trying to log into an account of mine using Selenium on with python.我正在尝试使用 Selenium 和 python 登录我的帐户。 When I write this code without object it works with no problems, but when I start to implement a class I get the error:当我在没有 object 的情况下编写此代码时,它没有问题,但是当我开始实现 class 时,我收到错误:

name 'driver' not defined

It' weird because before I get the error 'driver' is already called 1 time.这很奇怪,因为在我收到错误之前,“驱动程序”已经被调用了 1 次。

The code looks like this:代码如下所示:

class my_bot:
def __init__(self):

    self.driver = webdriver.Safari()
    self.driver.get('https://website.com')

def login(self, email, password):

    self.email = email
    self.password = password

    wait = WebDriverWait(self.driver, 10)

    fb_btn = wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="modal-manager"]/div/div/div/div/div[3]/span/div[2]/button')))
    self.driver.execute_script("arguments[0].click()", fb_btn)
    sleep(3)

    #switch the window

    base_window = self.driver.window_handles[0]
    self.driver.switch_to_window(driver.window_handles[1])

I get the error on the last line even though the call of 'driver' already happened before.即使“驱动程序”的调用之前已经发生,我在最后一行得到错误。

Has anyone an idea why this isnt working?有谁知道为什么这不起作用?

You can use below code while switching to new window.您可以在切换到新的 window 时使用以下代码。 it will help you to get the window handle after a new window has opened新的 window 打开后,它将帮助您获得 window 手柄

self.driver.switch_to_window(self.driver.window_handles[1])

add self.添加自我。

self.driver.switch_to_window(driver.window_handles[1]) -> self.driver.switch_to_window(self.driver.window_handles[1]) self.driver.switch_to_window(driver.window_handles[1]) -> self.driver.switch_to_window(self.driver.window_handles[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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