Home > Software engineering >  How to pass variables to driver execute script?
How to pass variables to driver execute script?

Time:12-10

I'm trying to pass some variables to js executor, but no luck. I've tried just about everything, but although it prints variables, the executor just doesn't do anything on webpage.

Here's the code:

    strings = ["ABC","DEF"]

elems = [i.text for i in driver.find_elements_by_xpath(title)]

import itertools
from json import dumps

for string, elem in zip(strings, elems):
    print(string, elem)

    driver.execute_script("arguments[0].innerHTML = '{}'".format(string), elem)
   # driver.execute_script("arguments[0].innerHTML = '   dumps(string)'", elem)
   # driver.execute_script("arguments[0].innerHTML = arguments[1]", string, elem)
    time.sleep(2)

CodePudding user response:

If you want to use innerHTML then you should use i instead of i.text.

And if you want to use arguments[1] then you have to use values in execute_script(...) in defferent order elem,string instead of string,elem

from selenium import webdriver
             
url = 'http://stackoverflow.com/'

driver = webdriver.Firefox()
driver.get(url)
 
strings = ["ABC", "DEF"]

title = '//title'
elems = driver.find_elements_by_xpath(title)

for string, elem in zip(strings, elems):
    print(string, elem)

    # WORKS
    #driver.execute_script("arguments[0].innerHTML = '{}'".format(string), elem)
    
    # WORKS - needs different order `elem, string` instead of `string, elem`
    driver.execute_script("arguments[0].innerHTML = arguments[1]", elem, string)
    #time.sleep(2)

BTW:

If you want to append new text to existing title then you should use

"arguments[0].text  = arguments[1]"

It may need also to add space between old and new text

"arguments[0].text  = ' '   arguments[1]"
  • Related