为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪4524236 2022-08-25 15:11:16
我正在尝试使用EEL及其文档将数据从python发送到Javascript,但它似乎不起作用...我一直在我的html / js页面中得到空值。这是我所拥有的。基本上,我想获取BING壁纸的链接,并将其用作我的页面作为背景。但在那之前,我想先得到结果。必应派脚本:import bs4import requestsimport jsondef 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 eelfrom inc.bing import scrape_bingeel.init('web')myDef = scrape_bing()@eel.exposedef bingR():   return myDeftry:   eel.start('index.html', mode='chrome', host='localhost', port=8274)except (SystemExit, MemoryError, KeyboardInterrupt):   passprint ('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 回答

?
慕慕森

TA贡献1856条经验 获得超17个赞

不确定您是否不小心将代码格式错误,但它有点偏差。此外,您在不需要的时候导入了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();

网站\索引.html


<!doctype html>

<html>

<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>

也感谢您向我介绍鳗鱼。第一次使用它,真的很喜欢它:)


查看完整回答
反对 回复 2022-08-25
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信