使用EEL将数据从Python发送到Javascript

3

我正在尝试使用EEL从Python将数据发送到JavaScript,但根据他们的文档,似乎无法正常工作...... 我在我的HTML / JS页面中一直得到null。

这是我所拥有的。 基本上,我想获取BING壁纸的链接并在我的页面中用作背景。 但在那之前,我要先获取结果。

BING Py脚本:

import bs4
import requests
import json


def scrape_bing():
   BASE_PATH = 'http://www.bing.com'
   BASE_REST = '/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US'
   URL = BASE_PATH + BASE_REST

   r = requests.get(url=URL)

   if r.status_code == 200:
      data = r.json()
      wallpaper_path = BASE_PATH + data['images'][0]['url']
      print(wallpaper_path)
   else:
      raise ValueError("[ERROR] non-200 response from Bing server for '{}'".format(URL))

   def main():
      scrape_bing()

   if __name__ == '__main__':
      main()

脚本运行正常,Python控制台返回了我的URL。 我的main.py带有EEL,代码如下:
import eel
from inc.bing import scrape_bing

eel.init('web')

myDef = scrape_bing()

@eel.expose
def bingR():
   return myDef

try:
   eel.start('index.html', mode='chrome', host='localhost', port=8274)

except (SystemExit, MemoryError, KeyboardInterrupt):
   pass

print ('Closed browser log...!')

我已经像他们的示例那样使用了异步命令,例如:

    <script type="text/javascript" src="/eel.js"></script>
    <script type="text/javascript">

    async function run() {
        let n = await eel.bingR()();
        console.log('Got this from Python: ' + n);
    }

    run();

    </script>

请帮助我理解这一切是如何运作的。
1个回答

9

不确定您是否意外格式化错误了代码,但它有点偏差。此外,您导入了bs4和json,但并不需要。

您的scrape_bing()函数没有返回任何内容。在“myDef = scrape_bing()”赋值时,它需要返回一个值给“myDef”。

我稍微修改了您的代码,并创建了以下示例,希望这能帮助您入门。


main.py

import eel
import requests

eel.init('web')

@eel.expose
def bingR():
    BASE_PATH = 'http://www.bing.com'
    BASE_REST = '/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US'
    URL = BASE_PATH + BASE_REST
    r = requests.get(url=URL)
    if r.status_code == 200:
        data = r.json()
        wallpaper_path = BASE_PATH + data['images'][0]['url']
        print(wallpaper_path)
        return wallpaper_path
    return 'No wallpaper found'

try:
    eel.start('index.html', mode='chrome', host='localhost', port=8274)
except (SystemExit, MemoryError, KeyboardInterrupt):
    pass

print ('Closed browser log...!')

web\myscript.js

async function run() {
    let n = await eel.bingR()();
    console.log('Got this from Python: ' + n);
    document.getElementById('output').value = n;
}
run();

web\index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Test</title>
</head>
<body>
  <script type="text/javascript" src="/eel.js"></script>
  <script type="text/javascript" src="/myscript.js"></script>
  <input id="output" value="Output here" style="width: 700px;">
</body>
</html>

感谢您介绍给我eel。第一次使用它,真的很喜欢:)


1
谢谢ScamCast,一切都像魔法般地运行。我想将Bing代码添加到一个单独的文件中,然后将其附加到主屏幕上,但我似乎搞砸了。我想创建一个桌面应用程序,EEL似乎是正确的选择,因为它允许您使用HTML + CSS :) - FBK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接