Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error selenium.common.exceptions.JavascriptException: Message: ReferenceError: room is not defined

I was trying to automate a web based API (haxball api) using python and selenium there were two steps

  1. After visiting https://html5.haxball.com/headless using your browser console F12 button and execute this var room = window.HBInit({ roomName: 'botts', maxPlayers: 16 });. After executing a captcha will appear we have to solve it manually.

  2. After solving you have to execute another script room.getPlayerList(); it will return an array back.

When I manually (using browser and console) do both steps, it works perfectly, but when I automate as using the code below (solving captcha manually at the 15 second interval) it is giving an error after the 15 second wait time (7th line).

from selenium import webdriver
import time
driver=webdriver.Firefox()
driver.get("https://html5.haxball.com/headless")
time.sleep(5)
driver.execute_script("var room = window.HBInit({ roomName: 'botts', maxPlayers: 16 });")
time.sleep(15)
driver.execute_script("room.getPlayerList();")

The first Javascript executes fine but the second driver.execute_script("room.getPlayerList();") gives an error:

"selenium.common.exceptions.JavascriptException: Message: ReferenceError: room is not defined"

but both the Javascript commands execute successfully when I enter them through the browser console one by one.

like image 388
Rudy Avatar asked Oct 16 '22 17:10

Rudy


1 Answers

you can use it only together

from selenium import webdriver
driver=webdriver.Firefox()
driver.get('url')
driver.execute_script("""
    var foo = 'this is a test';
    console.log(foo);
""")

Update

but if we want to get our variable in another execute_script method we can defined our variables in window for example:

from selenium import webdriver
driver=webdriver.Firefox()
driver.get('url')
driver.execute_script("""
    window.foo = 'Window variable';
""")

# some code

driver.execute_script("""
    console.log(window.foo);
""")

Output

# In console
Window variable
like image 155
Druta Ruslan Avatar answered Oct 27 '22 11:10

Druta Ruslan