Christo
Christo

Reputation: 15

Selenium - How to fix execute_script not returning any values after executing multiple javascript statements

I want to return a string using execute_script to my python script, but I am not getting any string from my execute_script function

I tried a variation of my code that didn't work. Console.logging my code in chrome dev tools console works.

Here is my Python code that I am trying to execute. I expect the javascript variable to have a string inside, but it is empty.

javaScript = driver.execute_script('proposedProRata = document.querySelectorAll("#ProposedPercent")' + 'proposedProRataStr = ""' + 'for (let i = 0, element; element = proposedProRata[i++];) { proposedProRataStr = proposedProRataStr + element.value + " " }' + 'proposedProRataStr')

I expect a string proposedProRataStr to be returned so I can use it in my Python code, but I am not getting any string returned, with no error messages

Upvotes: 0

Views: 234

Answers (1)

supputuri
supputuri

Reputation: 14145

Here is the simple way to loop through all the matching elements and then return the value.

javascript = '''var proposedProRataStr = ""; document.querySelectorAll("#ProposedPercent").forEach(function(el) {proposedProRataStr = proposedProRataStr + el.value + " "});return proposedProRataStr; '''
jsOutput = driver.execute(javascript)
print(jsOutput)

Once you write the working code in the browser console, just wrap the entire javascript in ''' (so that you don't have to worry about handling the double quotes.

Upvotes: 1

Related Questions