Return the value from within the Selenium execute_script

Asked

Viewed 240 times

0

Hello, I wrote this code below, and I would like to return the value of the drive.execute_script. I know the value is 3 from the console.log(i), but this value can change, and I want to go back inside python, how would you do that?

```import time
import requests
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import json

url = "https://shadowarena.pearlabyss.com/en-US/Arena?battleType=0&server=sa"
option = Options()
option.headless = True
driver = webdriver.Firefox()
driver.get(url)
driver.execute_script(''' 

const ranking = document.querySelectorAll('div.thum_name')

for(var i = 0; i < ranking.length; i++){
    var nick = document.querySelectorAll('div.thum_name')[i].innerText
    if(nick === "YoDaSL"){
        console.log(i)
    }

}
```


    ''')

time.sleep(10)
driver.quit()

1 answer

1

There are two ways you can get the javascript value into Python with Selenium:

1) Change Javascript to return the value:

Example:

output = driver.execute_script("return 30")
print(output)
=> 30

2) To get from the.log() console, you have to enable the browser log and pick up the log response. Example:

# Habilitando o log no Firefox
d = DesiredCapabilities.FIREFOX
d['loggingPrefs'] = {'browser': 'ALL'}
driver = webdriver.Firefox(capabilities=d)
#driver.get(url)
driver.execute_script("console.log(30)")
# buscando todos os dados do log
for entry in driver.get_log('browser'):
    print(entry['message'])
=> 30 (:) 

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.