I was trying to automate a web based API (haxball api) using python and selenium there were two steps
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With