如何从浏览器中获取Python读取变量?

时间:2022-07-09 22:59:04

On a school project, I am trying to code an AI to a simple game. The problem is that the game is a javascript code running in a browser, while the AI is to be coded with Python.

在学校项目中,我试图将AI编码为一个简单的游戏。问题是游戏是在浏览器中运行的javascript代码,而AI是用Python编码的。

I have isolated the useful real-time variables (like position, speed...) in the .js file, and I was able to output them in the browser debug console.

我已经在.js文件中隔离了有用的实时变量(如位置,速度......),并且我能够在浏览器调试控制台中输出它们。

How could I have Python access those variables, in real time?

我怎么能让Python实时访问这些变量?

Edit: To make myself more clear, I am trying to beat Chromium's T-Rex Runner. Here is my modified version, showing useful informations in the console: https://github.com/17maxd/t-rex-runner/ .

编辑:为了让自己更清楚,我试图击败Chromium的T-Rex Runner。这是我的修改版本,在控制台中显示有用的信息:https://github.com/17maxd/t-rex-runner/。

1 个解决方案

#1


0  

Two solutions come through my mind:

我想到了两个解决方案:

  1. The game's server code may expose API (e.g. REST API) via which your AI could query parameters and execute commands.
  2. 游戏的服务器代码可以公开API(例如REST API),您的AI可以通过它查询参数和执行命令。

  3. Make your AI interact with game just like human would using selenium-python
  4. 让人工智能与人类使用selenium-python进行人工互动

Using Selenium you can read state at any time by executing JS in browser like this (assuming your page includes jQuery):

使用Selenium,您可以随时通过在浏览器中执行JS来读取状态(假设您的页面包含jQuery):

from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get('http://example.com')

some_value = driver.execute_script('return $("#some_id").val();')

driver.close()

#1


0  

Two solutions come through my mind:

我想到了两个解决方案:

  1. The game's server code may expose API (e.g. REST API) via which your AI could query parameters and execute commands.
  2. 游戏的服务器代码可以公开API(例如REST API),您的AI可以通过它查询参数和执行命令。

  3. Make your AI interact with game just like human would using selenium-python
  4. 让人工智能与人类使用selenium-python进行人工互动

Using Selenium you can read state at any time by executing JS in browser like this (assuming your page includes jQuery):

使用Selenium,您可以随时通过在浏览器中执行JS来读取状态(假设您的页面包含jQuery):

from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get('http://example.com')

some_value = driver.execute_script('return $("#some_id").val();')

driver.close()