![](/img/trans.png)
[英]selenium.common.exceptions.JavascriptException: Message: ReferenceError: variable is not defined
[英]Error selenium.common.exceptions.JavascriptException: Message: ReferenceError: room is not defined
我试图使用python和selenium自动化基于Web的API(haxball api)有两个步骤
使用浏览器控制台F12按钮访问https://html5.haxball.com/headless后执行此var room = window.HBInit({ roomName: 'botts', maxPlayers: 16 });
。 执行验证码后,我们必须手动解决它。
解决后你必须执行另一个脚本room.getPlayerList();
它将返回一个数组。
当我手动(使用浏览器和控制台)执行这两个步骤时,它完美地工作,但是当我使用下面的代码自动执行(在15秒间隔手动解决验证码)时,它在15秒等待时间后给出错误(第7行) )。
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();")
第一个Javascript执行正常,但第二个driver.execute_script("room.getPlayerList();")
给出错误:
“selenium.common.exceptions.JavascriptException:消息:ReferenceError:未定义房间”
但是当我通过浏览器控制台逐个输入时,两个Javascript命令都会成功执行。
你只能在一起使用它
from selenium import webdriver
driver=webdriver.Firefox()
driver.get('url')
driver.execute_script("""
var foo = 'this is a test';
console.log(foo);
""")
更新
但是如果我们想在另一个execute_script
方法中获取变量,我们可以在window
定义我们的变量,例如:
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);
""")
产量
# In console
Window variable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.