错误selenium.common.异常.JavascriptException:消息:ReferenceError:未定义房间

2024-09-30 08:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用python和selenium自动化基于web的API(haxball API) 有两个步骤

  1. 使用浏览器控制台F12按钮访问https://html5.haxball.com/headless并执行var room = window.HBInit({ roomName: 'botts', maxPlayers: 16 });。 在执行验证码之后,我们必须手动解决它。

  2. 解决后,您必须执行另一个脚本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: Message: ReferenceError: room is not defined"

但是当我通过浏览器控制台逐一输入时,这两个Javascript命令都能成功执行。在


Tags: httpscomapiexecutetimedriverseleniumscript
1条回答
网友
1楼 · 发布于 2024-09-30 08:19:47

你只能一起用

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中定义变量,例如:

^{pr2}$

输出

# In console
Window variable

相关问题 更多 >

    热门问题