非常抱歉导致了这个问题。事实上,获取cookies的过程需要一些时间,以便完成浏览器加载页面并向服务器发送请求的过程。为此,我们需要在代码中添加等待步骤,以确保获取到完整的cookies数据。
以下是更新后的代码,其中使用了显式等待来确保页面加载完成后获取cookies:
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QComboBox, QPushButton, QLabel, QLineEdit, QFileDialog
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class BrowserCookies(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Browser Cookies")
layout = QVBoxLayout()
self.browser_combo = QComboBox()
self.browser_combo.addItems(["Microsoft Edge", "Chrome", "Firefox"]) # 添加浏览器选项
layout.addWidget(self.browser_combo)
self.website_edit = QLineEdit()
layout.addWidget(self.website_edit)
self.select_button = QPushButton("获取Cookies")
self.select_button.clicked.connect(self.get_cookies)
layout.addWidget(self.select_button)
self.label = QLabel()
layout.addWidget(self.label)
self.setLayout(layout)
def get_cookies(self):
browser_text = self.browser_combo.currentText()
website_url = self.website_edit.text() # 获取用户输入的网站URL
options = webdriver.EdgeOptions() # 默认为Microsoft Edge
if browser_text == "Chrome":
options = webdriver.ChromeOptions()
elif browser_text == "Firefox":
options = webdriver.FirefoxOptions()
browser_path = self.get_browser_path(options) # 获取浏览器路径
cookies_path = self.get_cookies_path(website_url) # 获取保存cookies的路径
cookies = self.fetch_cookies(browser_path, website_url) # 获取指定网站cookies
with open(cookies_path, "w") as file:
for cookie in cookies:
file.write(f"{cookie}={cookie}\n")
self.label.setText(f"{website_url}的Cookies已保存至:{cookies_path}")
def get_browser_path(self, options):
driver = webdriver.Edge(options=options)
browser_path = driver.capabilities["edge"]["binary"] # 获取浏览器路径(以Edge为例)
driver.quit()
return browser_path
def fetch_cookies(self, browser_path, website_url):
driver = webdriver.Edge(executable_path=browser_path)
driver.get(website_url)
# 等待页面加载完毕
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
cookies = driver.get_cookies()
driver.quit()
return cookies
def get_cookies_path(self, website_url):
cookies_path = f"E:/Temp/{website_url}_Cookies.txt"
return cookies_path
if __name__ == "__main__":
app = QApplication()
window = QMainWindow()
widget = BrowserCookies()
window.setCentralWidget(widget)
window.show()
app.exec()
请注意,我们添加了以下导入:from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
然后在`get_cookies`方法中,我们使用`WebDriverWait`和`expected_conditions`来等待页面加载完成:wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
这样的话,在执行获取cookies之前,我们会等待页面加载完成,然后再进行获取操作。最后,代码会将cookies保存在指定路径下。
希望这次的更新修复了问题。如有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |