selenium.common.exceptions.WebDriverException: Message: unknown error: 'script' must be a string while using execute_script() through Selenium Python

后端 未结 3 1385
温柔的废话
温柔的废话 2021-01-25 14:41

I\'ve got an issue with browser.execute_script while using selenium with python. There is an element that i\'d like to click (it\'s xpath below)

\"//*[@id=\'lis         


        
3条回答
  •  孤独总比滥情好
    2021-01-25 14:57

    This error message...

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

    ...implies that the method execute_script() was invoked with wrong type of parameters.

    The execute_script() method is defined as:

    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.
    

    In your code trial executeScript() method will take the reference of the element as arguments[0] along with the method to be performed (in this case click()) and the reference should be provided thereafter. So @Andersson's solution should have worked.

    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)
    

    You can find a detailed discussion in What does argument [0] and argument [1] mean in javascriptexecutor in Selenium WebDriver?


    The hint to your main issue is the error element not visible which implies either of the following cases:

    • You are trying to invoke click() even before the element is visible/clickable
    • Element is not within the Viewport when click() was invoked.

    Solution

    Two pottential solutions will be as follows:

    • Induce WebDriverWait for the element to be clickable as follows:

      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() method to bring the element within the Viewport and then invoke click() as follows:

      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()
      

提交回复
热议问题