是否可以在GraalVM示例中将对象从Python应用程序共享到Java应用程序?

fdbelqdn  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(125)

我有一个Python应用程序,它使用Playwright导航到网页,提取cookie并将其存储在列表中。我想要的是将这个对象发送到在同一GraalVM示例中运行的Java应用程序,以便Java应用程序可以将cookie存储在数据库中。
下面是Python代码:

# extractCookies.py
from playwright.sync_api import sync_playwright

def extract_cookies():
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()
        page.goto('https://google.com')
        cookies = page.context.cookies()
        browser.close()
        return cookies

if __name__ == "__main__":
    extracted_cookies = extract_cookies()

字符串
这在GraalVM中是否可以通过Polyglot API或其他方式实现?

ui7jx7zq

ui7jx7zq1#

是的,你应该能够沿着这些路线做一些事情:

Context ctx = Context.newBuilder("python").allowAllAccess(true).build();
        
        // Evaluates the script, which creates the extract_cookies Python function at the "top level"
        ctx.eval(Source.newBuilder("python", new File("extractCookies.py")).build());
        
        Value extract_cookies = ctx.getBindings("python").getMember("extract_cookies");
        Value extracted_cookies = extract_cookies.execute();
        
        // Let's say the result is a Python list:
        extracted_cookies.getArrayElement(0); // to get the first element
        extracted_cookies.getArraySize(); // to get the size
        
        // Let's say it is not a list, but can be iterated:
        Value iterator = extracted_cookies.getIterator();
        while (iterator.hasIteratorNextElement()) {
            Value element = iterator.getIteratorNextElement();
            // ...
        }

字符串

相关问题