使用EEL实现Python向JavaScript传值失败,返回null求助
Let's break down exactly why you're getting null and fix this step by step—plus I'll explain the underlying EEL and Python behavior so you understand what's going on.
The Core Issues
1. Your scrape_bing() Function Doesn't Return Data
Right now, your Python function only prints the wallpaper URL to the console—it never sends that value back to the code that calls it. In Python, any function without an explicit return statement automatically returns None. So when you run myDef = scrape_bing(), myDef becomes None, which EEL converts to JavaScript's null when sent across the bridge.
2. Incorrect EEL Function Call in JavaScript
EEL exposes Python functions as async functions in JS that return a Promise. Your code uses await eel.bingR()()—the extra () is redundant and incorrect. You only need to await the exposed function directly.
Fixed Code Examples
Updated scrape_bing.py
Add a return statement to pass the wallpaper URL back:
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) return wallpaper_path # Critical: return the URL here else: raise ValueError("[ERROR] non-200 response from Bing server for '{}'".format(URL)) def main(): scrape_bing() if __name__ == '__main__': main()
Updated main.py
I also removed the pre-assigned myDef—it's better to call scrape_bing() directly when the JS requests it, so you don't fetch the wallpaper once at startup (and potentially cache an old URL):
import eel from inc.bing import scrape_bing eel.init('web') @eel.expose def bingR(): try: return scrape_bing() # Call the scraper and return its result except Exception as e: print(f"Error fetching wallpaper: {e}") return None # Return None on failure for JS to handle try: eel.start('index.html', mode='chrome', host='localhost', port=8274) except (SystemExit, MemoryError, KeyboardInterrupt): pass print('Closed browser log...!')
Updated JavaScript Code
Fix the EEL call and add error handling + background image setup:
<script type="text/javascript" src="/eel.js"></script> <script type="text/javascript"> async function run() { try { const wallpaperUrl = await eel.bingR(); // Correct EEL call console.log('Got this from Python:', wallpaperUrl); // Set the wallpaper as page background if we got a valid URL if (wallpaperUrl) { document.body.style.backgroundImage = `url(${wallpaperUrl})`; document.body.style.backgroundSize = 'cover'; document.body.style.backgroundPosition = 'center'; } } catch (error) { console.error('Failed to fetch Bing wallpaper:', error); } } run(); </script>
Key Principles Explained
- Python Return Values: Always explicitly return data from functions that need to pass values to other code. Without
return, you getNone, which translates tonullin JS via EEL. - EEL Async Bridge: EEL uses async communication between Python and JS. Exposed Python functions become Promise-based in JS, so you must use
await(or.then()) to get the resolved value. - Error Handling: Wrapping calls in
try/catch(Python) andtry/catch(JS) prevents unexpected failures from breaking your app—critical for web scrapers that depend on external APIs.
内容的提问来源于stack exchange,提问作者FBK

