selenium.common.exceptions.WebDriverException:消息:未知错误:通过 Selenium Python 使用execute_script() 时,“script”必须是字符串

2023-12-05

在将 selenium 与 python 一起使用时,我遇到了 browser.execute_script 的问题。我想单击一个元素(下面是 xpath)

"//*[@id='listFav_FI410_23244709400000_FAGNNURROR_IPOF_APP_P43070_W43070A_CP000A001_40']/table/tbody/tr/td[1]"

我尝试这样做:

navMenu = browser.find_element_by_xpath("//*[@id='listFav_FI410_23244709400000_FAGNNURROR_IPOF_APP_P43070_W43070A_CP000A001_40']/table/tbody/tr/td[1]")
time.sleep(3)
browser.execute_script(navMenu.click())

它可以工作(因此它单击所需的元素),但在执行此操作后它会抛出一个错误并终止脚本:

selenium.common.exceptions.WebDriverException: Message: unknown error: 'script' must be a string

我究竟做错了什么?有没有办法跳过这个错误?谢谢你浪费时间来帮助我:)


这个错误信息...

selenium.common.exceptions.WebDriverException: Message: unknown error: 'script' must be a string

...意味着该方法execute_script()被调用错误的类型参数。

The execute_script()方法定义为:

execute_script(script, *args)
    Synchronously Executes JavaScript in the current window/frame.

Where:
    script: The JavaScript to execute
    *args: Any applicable arguments for your JavaScript.

在您的代码试用中executeScript()方法将把元素的引用作为参数[0]以及要执行的方法(在本例中click()) 并应在其后提供参考。所以@Andersson 的解决方案应该有效。

navMenu = browser.find_element_by_xpath("//*[@id='listFav_FI410_23244709400000_FAGNNURROR_IPOF_APP_P43070_W43070A_CP000A001_40']/table/tbody/tr/td[1]")
browser.execute_script("arguments[0].click()", navMenu)

您可以在中找到详细的讨论Selenium WebDriver 的 javascriptexecutor 中的参数 [0] 和参数 [1] 是什么意思?


您的主要问题的提示是错误element not visible这意味着以下任一情况:

  • 您正在尝试调用click()甚至之前该元素可见/可点击
  • 元素不在范围内Viewport when click()被调用。

Solution

两种可能的解决方案如下:

  • Induce WebDriver等待为了元素可点击如下:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    # other lines of code
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='listFav_FI410_23244709400000_FAGNNURROR_IPOF_APP_P43070_W43070A_CP000A001_40']/table/tbody/tr/td[1]"))).click()
    
  • Use executeScript()方法将元素带入Viewport然后调用click()如下:

    navMenu = browser.find_element_by_xpath("//*[@id='listFav_FI410_23244709400000_FAGNNURROR_IPOF_APP_P43070_W43070A_CP000A001_40']/table/tbody/tr/td[1]")
    browser.execute_script("arguments[0].scrollIntoView(true);",navMenu);
    navMenu.click()
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

selenium.common.exceptions.WebDriverException:消息:未知错误:通过 Selenium Python 使用execute_script() 时,“script”必须是字符串 的相关文章

随机推荐