【问题标题】:Error selenium.common.exceptions.JavascriptException: Message: ReferenceError: room is not defined错误 selenium.common.exceptions.JavascriptException:消息:ReferenceError:未定义房间
【发布时间】:2018-11-24 11:38:01
【问题描述】:

我正在尝试使用 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:消息:ReferenceError:房间未定义”

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

【问题讨论】:

    标签: javascript python api selenium automation


    【解决方案1】:

    只能一起使用

    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
    

    【讨论】:

    • 但是第二个 java 脚本需要在第一个之后的某个时间后执行。
    • @Rudy 我找到了解决方案,试试这个
    • 这很好用,但是我如何将第二次执行的输出存储到变量中?
    • 试试这个driver.execute_script(" window.playerList = room.getPlayerList();"),你可以在window里面放很多你想要的变量
    猜你喜欢
    • 2020-09-11
    • 2022-01-05
    • 2020-02-22
    • 2021-06-03
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多