非常抱歉,我再次检查了代码,并发现遗漏了一个重要的步骤。我们需要在页面加载完成后才能获取到cookies。以下是更新后的代码,应该可以正常地获取并保存cookies:
import os
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QComboBox, QPushButton, QLabel
from PySide6.QtCore import Qt, Slot
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import EdgeOptions
from msedge.selenium_tools import Edge
class BrowserCookies(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Cookies获取工具")
self.setFixedSize(400, 200)
# 创建主窗口
main_widget = QWidget(self)
layout = QVBoxLayout(main_widget)
# 创建浏览器选择下拉菜单
self.browser_combo = QComboBox()
self.browser_combo.addItems(["Microsoft Edge", "Chrome", "Firefox"])
layout.addWidget(self.browser_combo)
# 创建录入网站的标签和文本框
website_label = QLabel("请输入要获取cookies的网站:")
layout.addWidget(website_label)
self.website_text = QLineEdit()
layout.addWidget(self.website_text)
# 创建获取cookies按钮
get_cookies_button = QPushButton("获取cookies")
get_cookies_button.clicked.connect(self.get_cookies)
layout.addWidget(get_cookies_button)
# 设置主窗口布局
self.setCentralWidget(main_widget)
@Slot()
def get_cookies(self):
browser_index = self.browser_combo.currentIndex()
browser_path = ""
if browser_index == 0:
browser_path = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"
elif browser_index == 1:
browser_path = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
elif browser_index == 2:
browser_path = "C:\\Program Files\\Mozilla Firefox\\firefox.exe"
website_url = self.website_text.text()
cookies = self.fetch_cookies(browser_path, website_url) # 获取指定网站cookies
if cookies:
self.save_cookies(cookies) # 保存cookies到指定路径
QMessageBox.information(self, "提示", "Cookies获取成功!")
else:
QMessageBox.warning(self, "警告", "无法获取Cookies,请检查网站和浏览器设置!")
def fetch_cookies(self, browser_path, website_url):
service = Service("C:\MicrosoftWebDriver\msedgedriver.exe")
options = EdgeOptions()
options.binary_location = browser_path
driver = Edge(service=service, options=options)
driver.get(website_url)
driver.implicitly_wait(5)
cookies = driver.get_cookies()
driver.quit()
return cookies
def save_cookies(self, cookies):
file_path = os.path.join("E:\\Temp", "网站的Cookies.txt")
with open(file_path, "w") as f:
for cookie in cookies:
f.write(f"{cookie['name']}={cookie['value']}\n")
if __name__ == "__main__":
app = QApplication([])
window = BrowserCookies()
window.show()
app.exec()
请尝试使用这个修复后的代码,录入https://www.thepaper.cn/,点击"获取cookies"按钮后应该可以正常获取到cookies并保存在"E:\Temp"文件夹中。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |