PyQt5中QtWebEngine获取cookie的3种方式

1,072 阅读1分钟
  1. 直接从本地存储的cookie数据库中直接获取(能获取本地所有域名的cookie,并且获取的cookie最全)
  2. 重写QWebEngineView中onCookieAdd方法进行获取
  3. 通过页面js的方式获取当前域名的cookie

下边是三种方式获取cookie代码

# -*- coding: utf-8 -*
import os
import sqlite3
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile, QWebEnginePage
from PyQt5.QtWidgets import QApplication, QPushButton, QVBoxLayout, QWidget
import sys


class WebView(QWebEngineView):

    def __init__(self):
        super().__init__()
        name = "default"
        file = QWebEngineProfile(name, self)  # 不同名称保存不同用户
        webpage = QWebEnginePage(file, self)
        self.setPage(webpage)
        file.cookieStore().cookieAdded.connect(self.onCookieAdd)
        self.cookies = {}  # 存放cookie字典

    def createWindow(self, wintype):
        return self

    def onCookieAdd(self, cookie):  # 处理cookie添加的事件
        # logger.info(cookie)
        name = cookie.name().data().decode('utf-8')  # 先获取cookie的名字,再把编码处理一下
        value = cookie.value().data().decode('utf-8')  # 先获取cookie值,再把编码处理一下
        print("onCookieAdd", name, value)
        # self.cookies[name] = value  # 将cookie保存到字典里


class WebEngineView(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.setWindowTitle('测试例子')
        self.setGeometry(5, 30, 1355, 730)
        self.browser = WebView()
        # 加载外部页面
        self.browser.load(QUrl('https://www.baidu.com'))
        self.but1 = QPushButton("获取cookie1")
        self.but1.clicked.connect(self.local_get_cookie)
        self.but2 = QPushButton("获取cookie1")
        self.but2.clicked.connect(self.js_get_cookie)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.but1)
        self.layout.addWidget(self.but2)
        self.layout.addWidget(self.browser)
        self.setLayout(self.layout)

    def get_cookie1(self):
        print(self.get_cookie())

    # 从本地的缓存数据库中获取cookie
    def local_get_cookie(self):
        local = os.environ['LOCALAPPDATA']
        eng = os.path.join(local, 'python\QtWebEngine')
        tab_name = "default"
        base_url = os.path.join(eng, tab_name)
        cx = sqlite3.connect(os.path.join(base_url, "Cookies"))
        cu = cx.cursor()
        res = cu.execute("select * from cookies;")
        items = {}
        for item in res:
            print(item)
            name = item[2]
            v = item[3]
            items[name] = v
        return items

    def js_get_cookie(self):
        js_string = '''
                function myFunction()
                {
                    return document.cookie
                }
                myFunction()
                '''
        self.browser.page().runJavaScript(js_string, self.js_cookie)

    def js_cookie(self, cookie):
        print(f"js_cooke:{cookie}")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = WebEngineView()
    win.show()
    sys.exit(app.exec_())