python-3.x 在PyWebView中关闭窗口后无法获取cookie

pcww981p  于 2023-01-27  发布在  Python
关注(0)|答案(1)|浏览(283)

调用webview.start、关闭窗口并调用window.get_cookies函数后,我收到以下错误:* * 键错误:"主服务器"**
追溯:

Traceback (most recent call last):
  File "D:\better_gui.py", line 34, in <module>
    )
      
  File "D:\venv-python\Lib\site-packages\webview\window.py", line 36, in wrapper
    return function(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\venv-python\Lib\site-packages\webview\window.py", line 237, in get_cookies
    return self.gui.get_cookies(self.uid)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\venv-python\Lib\site-packages\webview\platforms\winforms.py", line 646, in get_cookies
    window = BrowserView.instances[uid]
             ~~~~~~~~~~~~~~~~~~~~~^^^^^
KeyError: 'master'

我用的是Python 3.11
我的代码:

import webview
import sys
import urllib.request

window = webview.create_window(
    sys.argv[2],
    sys.argv[1],
    width=1280,
    height=720,
    min_size=(1280, 720)
)

webview.start(
    private_mode=False,
    storage_path='.\\gui'
)

cookies = window.get_cookies()

url = f'{sys.argv[1]}/close?cookie={cookies}'
urllib.request.urlopen(url)

我还尝试添加事件处理程序window.events.closing += on_closing,函数设置如下:

import webview
import sys
import urllib.request

def on_closing() -> None:
    cookies = window.get_cookies()

    url = f'{sys.argv[1]}/close?cookie={cookies}'
    urllib.request.urlopen(url)

window = webview.create_window(
    sys.argv[2],
    sys.argv[1],
    width=1280,
    height=720,
    min_size=(1280, 720)
)

window.events.closing += on_closing

webview.start(
    private_mode=False,
    storage_path='.\\gui'
)

但窗口崩溃,Windows无法终止进程。

aurhwmvo

aurhwmvo1#

如何使用cookiejar作为在下面的例子:

import requests
import http.cookiejar
import urllib
    
def on_closing() -> None:
    url = f'{sys.argv[1]}/close?cookie={cookies}'
    urllib.request.urlopen(url)
    cookies = http.cookiejar.CookieJar()
            url_opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookies))
            url_opener.open(url)
            for cookie in cookies:
                print(cookie.name, cookie.value)
window = webview.create_window(
    sys.argv[2],
    sys.argv[1],
    width=1280,
    height=720,
    min_size=(1280, 720)
)

window.events.closing += on_closing

webview.start(
    private_mode=False,
    storage_path='.\\gui'
)

相关问题