将变量作为参数传递给 selenium find_element 函数而不是硬编码参数会导致 InvalidArgumentException

Passing a variable as argument to selenium find_element function instead of hardcoded argument results in a InvalidArgumentException

上下文

我将 selenium 与 python 一起使用,并试图将 PageObjectsofficial selenium documentation 之后的代码分开,但我收到一个我不理解的错误:

from selenium.webdriver.common.by import By

class MainPageLocators(object):
    """A class for main page locators. All main page locators should come here"""
    GO_BUTTON = (By.ID, 'submit') 

像上面那样做会给我一个 selenium.common.exceptions.InvalidArgumentException: Message: expected value at line 1 column 11 错误。

正在复制

我使用 Google 主页重现了错误:

from selenium import webdriver
from selenium.webdriver.common.by import By


def test():
    driver = webdriver.Firefox()
    driver.get('https://www.google.com')

    element = (By.NAME, "btnK")
    driver.find_element(element)


if __name__ == "__main__":
    test()

完整错误:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    test()
  File "test.py", line 10, in test
    driver.find_element(element)
  File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: expected value at line 1 column 11

有趣的是,直接在 find_element 函数中传递参数,效果很好。

def test():
    driver = webdriver.Firefox()
    driver.get('https://www.google.com')

    element = ()
    driver.find_element(By.NAME, "btnK")

环境

OS: Windows 10 浏览器:火狐 浏览器版本:77.0.1 浏览器驱动版本:GeckoDriver 0.26 语言绑定版本:Python 3.6,python-selenium 3.141.0 Selenium Grid 版本(如果适用):

GeckoDriver 日志

1593341659616   mozrunner::runner   INFO    Running command: "C:\Program Files\Mozilla Firefox\firefox.exe" "-marionette" "-foreground" "-no-remote" "-profile" "C:\Users\xxx\AppData\Local\Temp\rust_mozprofileNZPCZw"
JavaScript error: resource://gre/modules/XULStore.jsm, line 66: Error: Can't find profile directory.
1593341663463   Marionette  INFO    Listening on port 62786
1593341663826   Marionette  WARN    TLS certificate errors will be ignored for this session
JavaScript error: resource://gre/modules/NetworkGeolocationProvider.jsm, line 555: TypeError: xhr.response.location is undefined

如何解决这个错误?

两者的区别

driver.find_element(By.NAME, "btnK")

args = (By.NAME, "btnK")
driver.find_element(args)

就是第一个版本发送两个参数,第二个版本发送一个参数(一个元组)。

使用 * 运算符“解压”参数:

args = (By.NAME, "btnK")
driver.find_element(*args)