class CookieStore(object): def __init__(self): self._cookie_jar = QNetworkCookieJar() def add(self, cookie_dict, scheme, hostname, path="/"): cookie_list = [] for key, value in cookie_dict.items(): cookie = QNetworkCookie() cookie.setDomain(hostname) cookie.setPath(path) key_b = QByteArray() key_b.append(key) cookie.setName(key_b) value_b = QByteArray() value_b.append(value) cookie.setValue(value_b) cookie_list.append(cookie) self._cookie_jar.setCookiesFromUrl(cookie_list, QUrl(str(scheme))) def get(self, url): cookie_list = self._cookie_jar.cookiesForUrl(QUrl(url)) cookie_dict = {} for cookie in cookie_list: cookie_dict[cookie.name()] = cookie.value() return cookie_dict def clear(self, url): cookie_list = self._cookie_jar.cookiesForUrl(QUrl(url)) for cookie in cookie_list: cookie.setValue("") self._cookie_jar.setCookiesFromUrl(cookie_list, QUrl(url))
def set_cookies_from_url(self, cookies, url): """ Reimplementation from base class. Prevents cookies from being set if not from whitelisted domains. """ (_, domain, suffix) = extract(url.host()) site = domain + '.' + suffix if site not in self.allowed: if self.parent().show_detail: print("COOKIE FROM {} not set".format(url.toString())) # COO01 ret = [] else: print("SET COOKIE FROM {}".format(url.toString())) ret = cookies return QNetworkCookieJar.setCookiesFromUrl(self, ret, url)
def set_cookies_from_url(self, cookies, url): """ Reimplementation from base class. Prevents cookies from being set if not from whitelisted domains. """ (_, domain, suffix) = extract(url.host()) site = domain + '.' + suffix if site not in self.allowed: if self.parent().show_detail: print("COOKIE FROM {} not set".format(url.toString())) # COO01 ret = [] else: print("SET COOKIE FROM {}".format(url.toString())) ret = cookies return QNetworkCookieJar.setCookiesFromUrl(self, ret, url)
class LoginWindow(QWebEngineView): def __init__(self): super().__init__() self.setWindowIcon(QIcon(app_icon)) self.setWindowTitle('login') self.loadFinished.connect(self.process_load_finish) self.main_window = None self.is_login = False cookie_store = self.page().profile().cookieStore() print(cookie_store) self.cookiejar = QNetworkCookieJar() cookie_store.cookieAdded.connect(self.cookie_added) self.login_on_startup() def set_main_window(self, main_window): self.main_window = main_window def show(self): self.load(QUrl(longzhu_login_url)) super().show() def process_load_finish(self): if self.url().host() == 'www.longzhu.com' and self.url().path() == '/': print('after login') self.page().toHtml(self.login) def login(self, data): try: self.login_html = data user_menu = pq(data)('#topbar-user-menu') self.level = user_menu.find('i.user-lv').attr['class'].split( '-')[-1] self.uid = user_menu.find( 'a.report-rbi-click').attr['data-label'].split(':')[-1] self.username = user_menu.find('span.topbar-username').text() self.is_login = True print(self.level) print(self.uid) print(self.username) for cookie in self.cookiejar.cookiesForUrl( QUrl(longzhu_login_url)): print('name = {}, value = {}'.format( str(cookie.name(), encoding='ascii'), str(cookie.value(), encoding='ascii'))) self.main_window.login(self.username, self.level) self.load(QUrl('')) self.hide() self.save_cookie() except: pass def logout(self): self.level = '' self.uid = '' self.username = '' self.is_login = False self.cookiejar.setAllCookies([]) self.page().profile().cookieStore().deleteAllCookies() self.delete_cookie() def login_on_startup(self): if self.load_cookie(): self.load(QUrl('http://www.longzhu.com')) def cookie_added(self, cookie): if cookie.name() == b'p1u_id' or cookie.name() == b'PLULOGINSESSID': print('name = {}, domain = {}, value = {}, path = {}, date = {}'. format(cookie.name(), cookie.domain(), cookie.value(), cookie.path(), cookie.expirationDate().date())) self.cookiejar.setCookiesFromUrl([cookie], QUrl(longzhu_login_url)) def save_cookie(self): with open(cookie_file, 'wb') as f: for cookie in self.cookiejar.allCookies(): f.write(cookie.toRawForm() + b'\n') def delete_cookie(self): try: os.remove(cookie_file) except OSError: pass def load_cookie(self): cookies = [] if os.path.isfile(cookie_file): with open(cookie_file, 'rb') as f: for line in f: cookie = QNetworkCookie.parseCookies(line) self.cookiejar.setCookiesFromUrl(cookie, QUrl(longzhu_login_url)) self.page().profile().cookieStore().setCookie(cookie[0]) return True return False
def setCookiesFromUrl(self, cookieList, url): """ Public method to set cookies for a URL. @param cookieList list of cookies to set (list of QNetworkCookie) @param url url to set cookies for (QUrl) @return flag indicating cookies were set (boolean) """ if not self.__loaded: self.load() globalSettings = QWebSettings.globalSettings() if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled): return False host = url.host() eBlock = self.__isOnDomainList(self.__exceptionsBlock, host) eAllow = not eBlock and \ self.__isOnDomainList(self.__exceptionsAllow, host) eAllowSession = not eBlock and \ not eAllow and \ self.__isOnDomainList( self.__exceptionsAllowForSession, host) addedCookies = False acceptInitially = self.__acceptCookies != self.AcceptNever if (acceptInitially and not eBlock) or \ (not acceptInitially and (eAllow or eAllowSession)): # url domain == cookie domain soon = QDateTime.currentDateTime() soon = soon.addDays(90) for cookie in cookieList: lst = [] if not (self.__filterTrackingCookies and cookie.name().startsWith(b"__utm")): if eAllowSession: cookie.setExpirationDate(QDateTime()) if self.__keepCookies == self.KeepUntilTimeLimit and \ not cookie.isSessionCookie and \ cookie.expirationDate() > soon: cookie.setExpirationDate(soon) lst.append(cookie) if QNetworkCookieJar.setCookiesFromUrl(self, lst, url): addedCookies = True elif self.__acceptCookies == self.AcceptAlways: # force it in if wanted cookies = self.allCookies() for ocookie in cookies[:]: # does the cookie exist already? if cookie.name() == ocookie.name() and \ cookie.domain() == ocookie.domain() and \ cookie.path() == ocookie.path(): # found a match cookies.remove(ocookie) cookies.append(cookie) self.setAllCookies(cookies) addedCookies = True if addedCookies: self.__saveTimer.changeOccurred() self.cookiesChanged.emit() return addedCookies
def setCookiesFromUrl(self, cookieList, url): """ Public method to set cookies for a URL. @param cookieList list of cookies to set (list of QNetworkCookie) @param url url to set cookies for (QUrl) @return flag indicating cookies were set (boolean) """ if not self.__loaded: self.load() globalSettings = QWebSettings.globalSettings() if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled): return False host = url.host() eBlock = self.__isOnDomainList(self.__exceptionsBlock, host) eAllow = not eBlock and \ self.__isOnDomainList(self.__exceptionsAllow, host) eAllowSession = not eBlock and \ not eAllow and \ self.__isOnDomainList( self.__exceptionsAllowForSession, host) addedCookies = False acceptInitially = self.__acceptCookies != self.AcceptNever if (acceptInitially and not eBlock) or \ (not acceptInitially and (eAllow or eAllowSession)): # url domain == cookie domain soon = QDateTime.currentDateTime() soon = soon.addDays(90) for cookie in cookieList: lst = [] if not (self.__filterTrackingCookies and cookie.name().startsWith(b"__utm")): if eAllowSession: cookie.setExpirationDate(QDateTime()) if self.__keepCookies == self.KeepUntilTimeLimit and \ not cookie.isSessionCookie and \ cookie.expirationDate() > soon: cookie.setExpirationDate(soon) lst.append(cookie) if QNetworkCookieJar.setCookiesFromUrl(self, lst, url): addedCookies = True elif self.__acceptCookies == self.AcceptAlways: # force it in if wanted cookies = self.allCookies() for ocookie in cookies[:]: # does the cookie exist already? if cookie.name() == ocookie.name() and \ cookie.domain() == ocookie.domain() and \ cookie.path() == ocookie.path(): # found a match cookies.remove(ocookie) cookies.append(cookie) self.setAllCookies(cookies) addedCookies = True if addedCookies: self.__saveTimer.changeOccurred() self.cookiesChanged.emit() return addedCookies
def __init__(self, cookies, qt_url, parent=None): QNetworkCookieJar.__init__(self, parent) for cookie in cookies: QNetworkCookieJar.setCookiesFromUrl( self, QNetworkCookie().parseCookies(QByteArray(cookie)), qt_url)