首页 > 解决方案 > 使用 Google Chrome 的 selenium webdriver

问题描述

有没有人在尝试使用硒时遇到过同样的错误?

我正在从 venv 执行脚本,这是错误

self.driver = webdriver.Chrome(options=options)
TypeError: __init__() got an unexpected keyword argument 'options

这是代码

class LoginToSite ():
    def __init__(self, username, password):
        self.username = username
        self.password = password


        options = webdriver.chromeoptions(options=options)
        options.add_argument("--incognito")

        self.driver = webdriver.Chrome(options=options)
        self.driver.get('https://google.com')
        self.driver.get("https://portal.office.com")
        sleep(2)

        self.driver.find_element_by_id('i0116')\
            .send_keys(self.username)

        self.driver.find_element_by_id('idSIButton9').click()
        sleep(5)

        self.driver.find_element_by_id('passwordInput')\
            .send_keys(self.password)

        self.driver.find_element_by_id('submitButton').click()
        sleep(5)

        self.driver.find_element_by_id('idSIButton9').click()
        sleep(2)

        main_window = self.driver.window_handles[0]
        self.driver.find_element_by_id('ShellPowerApps_link_text').click()
        sleep(10)
        second_window = self.driver.window_handles[1]
        self.driver.switch_to_window(second_window)

        # self.driver.find_element_by_xpath("//img[contains(text(), '')]")\
        #     .click()
        self.driver.find_element_by_xpath("//a[contains(@href,'/apps')]")\
            .click()
        sleep(10)
        self.driver.find_element_by_xpath("//a[contains(@href,'/abc')]")\
            .click()
LoginToSite(uname,pw)

这是有道理的,因为我没有创建 options 变量,但这是建议的。

请帮忙。

标签: pythonseleniumselenium-webdriverselenium-chromedriver

解决方案


您的代码有问题: .

options = webdriver.chromeoptions(options=options)

您正在使用options而没有实际定义它。

解决方案
只需为 options() 创建一个对象。
所以而不是

options = webdriver.chromeoptions(options=options)

利用

options = Options()

最终代码应如下所示

options = Options()
options.add_argument("--incognito")
self.driver = webdriver.Chrome(options=options)

推荐阅读