2022年1月14日 星期五

What is arguments[0] while invoking execute_script() method through WebDriver instance through Selenium and Python?(轉貼)

Ref: https://stackoverflow.com/questions/52273298/what-is-arguments0-while-invoking-execute-script-method-through-webdriver-in/52280298#52280298

 I'm trying to crawl the pages that I interested in. For this, I need to remove attribute of element from HTML. 'style' is what I want to remove. So I find some codes from Stackoverflow.(i'm using Chrome for driver)

element = driver.find_element_by_xpath("//select[@class='m-tcol-c' and @id='searchBy']")
driver.execute_script("arguments[0].removeAttribute('style')", element)

What does arguments[0] do in the code? Can anyone explain arguments[0]'s roles concretely?


Ans:

arguments is what you're passing from Python to JavaScript that you want to execute.

driver.execute_script("arguments[0].removeAttribute('style')", element) 

means that you want to "replace" arguments[0] with WebElement stored in element variable.

This is the same as if you defined that element in JavaScript:

driver.execute_script("document.querySelector('select.m-tcol-c#searchBy').removeAttribute('style')")

You can also pass more arguments as

driver.execute_script("arguments[0].removeAttribute(arguments[1])", element, "style")
  • Note the word WebElement to be passed to the execute_scriptmethod. Passing the result from element(by.css(...)) directly causes CallStackSize error, that's why one has to use element(by.css(...)).getWebElement()  Jun 3 '21 at 12:57