当前位置: 首页>>代码示例>>Python>>正文


Python QNetworkCookieJar.setAllCookies方法代码示例

本文整理汇总了Python中PyQt4.QtNetwork.QNetworkCookieJar.setAllCookies方法的典型用法代码示例。如果您正苦于以下问题:Python QNetworkCookieJar.setAllCookies方法的具体用法?Python QNetworkCookieJar.setAllCookies怎么用?Python QNetworkCookieJar.setAllCookies使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PyQt4.QtNetwork.QNetworkCookieJar的用法示例。


在下文中一共展示了QNetworkCookieJar.setAllCookies方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _import_cookie_jar

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]
	def _import_cookie_jar(self,http_cookie_jar,default_domain):

		cj = QNetworkCookieJar()
		cookie_attrs = http_cookie_jar.http_header_attrs(self.urllib_request)
		cookies = self._parse_cookie_attribs_into_QtCookies_list(cookie_attrs, default_domain)
		cj.setAllCookies(cookies)
		return cj
开发者ID:thomaswar,项目名称:saml-testharness-mod-interactivebrowser,代码行数:9,代码来源:injector.py

示例2: ShoutCastForm

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]
class ShoutCastForm(PluginBase.PluginBase):
    '''Grab Shoutcast streams and save them as "bookmarks" - and play them on
       the currently selected server.

       General shoutcast information is not preserved between runs. Also, the
       shoutcast server/API is pretty lame so timeouts actually occur quite
       frequently.
    '''
    moduleName = '&Shoutcast'
    moduleIcon = "network-workgroup"

    def load(self):
        pass

    def event(self, event):
        if event.type() == QEvent.Paint:
            if not hasattr(self, 'webView'):
                self._load()
                self.event = super(ShoutCastForm, self).event
        return False

    def _load(self):
        self.cookie = QNetworkCookie('Settings', 'Player~others|Bandwidth~ALL|Codec~ALL')
        self.cookie.setDomain('.shoutcast.com')
        self.cookie.setExpirationDate(QDateTime())
        self.cookie.setPath('/')

        self.webView = QWebView(self)
        self.webPage = self.webView.page()
        self.cookiejar = QNetworkCookieJar()
        self.cookiejar.setAllCookies([self.cookie])
        self.webPage.networkAccessManager().setCookieJar(self.cookiejar)

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.webView)
        self.webView.load(QUrl(HOMEURL))
        self.webPage.setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)
        self.connect(self.webPage, SIGNAL('linkClicked(const QUrl&)'), self._processLink)

    def _processLink(self, url):
        if url.host() == TUNEIN:
            self._playStation(unicode(url.toString()))
        else:
            self.webView.load(url)
            self.webView.show()

    def _playStation(self, url):
        try:
            streamList = streamTools.getStreamList(url)
        except streamTools.ParseError:
            return
        if streamList:
            self.modelManager.playQueue.extend(streamList)
开发者ID:tarmack,项目名称:Pythagora,代码行数:55,代码来源:ShoutcastForm.py

示例3: load_cookies

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]
    def load_cookies(self, url, cookie_strings):
        p = urlparse(url)

        cookies = list()
        for c in cookie_strings:
            n = c.find('=')
            name, value = c[:n], c[n+1:]
            cookie = QNetworkCookie(name, value)
            cookie.setDomain(p.netloc)
            cookies.append(cookie)

        cookiejar = QNetworkCookieJar()
        cookiejar.setAllCookies(cookies)
        self.networkAccessManager().setCookieJar(cookiejar)
开发者ID:Aliandrana,项目名称:scripts,代码行数:16,代码来源:webkit_crawler.py

示例4: _createCookieJarfromInjectedResponse

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]
	def _createCookieJarfromInjectedResponse(self, default_domain):
		#ugly, but works around bugs in parseCookies
		cookies = []

		for cookie_header in self._getCookieHeaders():
			tmp_cookieList = QNetworkCookie.parseCookies(cookie_header)
			tmp_cookie = tmp_cookieList[0]
			if not tmp_cookie.domain():
				tmp_cookie.setDomain(QString(default_domain))

			cookies = cookies + tmp_cookieList

		cj = QNetworkCookieJar()
		cj.setAllCookies(cookies)
		return cj
开发者ID:thomaswar,项目名称:saml-testharness-mod-interactivebrowser-qt5,代码行数:17,代码来源:injector.py

示例5: _MozillaCookieJar_to_QnetworkCookieJar

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]
 def _MozillaCookieJar_to_QnetworkCookieJar(cookie_file):
         def line2qcookie(line):
                 domain,initial_dot,path,isSecure,expires,name,value=line.split()
                 isSecure=(isSecure=="TRUE")
                 dt=QDateTime()
                 dt.setTime_t(int(expires))
                 expires=dt
                 c=QNetworkCookie()
                 c.setDomain(domain)
                 c.setPath(path)
                 c.setSecure(isSecure)
                 c.setExpirationDate(expires)
                 c.setName(name)
                 c.setValue(value)
                 return c
         cj=QNetworkCookieJar()
         if os.path.exists(cookie_file):
                 cj.setAllCookies([line2qcookie(line) for line in open(cookie_file)  if not line.startswith("#") and line and not line.isspace()])
                 #~ print cj.allCookies()
         else:
                 raise IOError("File not found: %s"%cookie_file)
         return cj
开发者ID:mopperwhite,项目名称:tiebasigner,代码行数:24,代码来源:loginer.py

示例6: Kit

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]
class Kit(object):
    _app = None

    def __init__(self, gui=False):
        if not Kit._app:
            Kit._app = QApplication([])

        manager = KitNetworkAccessManager()
        manager.finished.connect(self.network_reply_handler)

        self.cookie_jar = QNetworkCookieJar()
        manager.setCookieJar(self.cookie_jar)

        self.page = KitPage()
        self.page.setNetworkAccessManager(manager)

        self.view = KitWebView()
        self.view.setPage(self.page)
        self.view.setApplication(Kit._app)

        if gui:
            self.view.show()

    def get_cookies(self):
        cookies = {}
        for cookie in self.cookie_jar.allCookies():
            cookies[cookie.name().data()] = cookie.value().data()
        return cookies

    def request(self, url, user_agent='Mozilla', cookies=None, timeout=15,
                method='get', data=None, headers=None):
        if cookies is None:
            cookies = {}
        if headers is None:
            headers = {}
        url_info = urlsplit(url)

        self.resource_list = []
        loop = QEventLoop()
        self.view.loadFinished.connect(loop.quit)

        # Timeout
        timer = QTimer()
        timer.setSingleShot(True)
        timer.timeout.connect(loop.quit)
        timer.start(timeout * 1000)

        # User-Agent
        self.page.user_agent = user_agent

        # Cookies
        cookie_obj_list = []
        for name, value in cookies.items():
            domain = ('.' + url_info.netloc).split(':')[0]
            #print 'CREATE COOKIE %s=%s' % (name, value)
            #print 'DOMAIN = %s' % domain
            cookie_obj = QNetworkCookie(name, value)
            cookie_obj.setDomain(domain)
            cookie_obj_list.append(cookie_obj)
        self.cookie_jar.setAllCookies(cookie_obj_list)

        # Method
        method_obj = getattr(QNetworkAccessManager, '%sOperation'
                             % method.capitalize())

        # Ensure that Content-Type is correct if method is post
        if method == 'post':
            headers['Content-Type'] = 'application/x-www-form-urlencoded'

        # Post data
        if data is None:
            data = QByteArray()

        # Request object
        request_obj = QNetworkRequest(QUrl(url))

        # Headers
        for name, value in headers.items():
            request_obj.setRawHeader(name, value)

        # Make a request
        self.view.load(request_obj, method_obj, data)

        loop.exec_()

        if timer.isActive():
            request_resource = None
            url = str(self.page.mainFrame().url().toString()).rstrip('/')
            for res in self.resource_list:
                if url == res.url or url == res.url.rstrip('/'):
                    request_resource = res
                    break
            if request_resource:
                return self.build_response(request_resource)
            else:
                raise KitError('Request was successful but it is not possible'
                               ' to associate the request to one of received'
                               ' responses')
        else:
            raise KitError('Timeout while loading %s' % url)
#.........这里部分代码省略.........
开发者ID:Scaurus,项目名称:grab,代码行数:103,代码来源:__init__.py

示例7: Ghost

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]

#.........这里部分代码省略.........
        """
        if not self.exists(selector):
            raise Exception("Can't find element to click")
        return self.evaluate('GhostUtils.click("%s");' % selector)

    class confirm:
        """Statement that tells Ghost how to deal with javascript confirm().

        :param confirm: A bollean that confirm.
        :param callable: A callable that returns a boolean for confirmation.
        """
        def __init__(self, confirm=True, callback=None):
            self.confirm = confirm
            self.callback = callback

        def __enter__(self):
            Ghost._confirm_expected = (self.confirm, self.callback)

        def __exit__(self, type, value, traceback):
            Ghost._confirm_expected = None

    @property
    def content(self):
        """Returns current frame HTML as a string."""
        return unicode(self.main_frame.toHtml())

    @property
    def cookies(self):
        """Returns all cookies."""
        return self.cookie_jar.allCookies()

    def delete_cookies(self):
        """Deletes all cookies."""
        self.cookie_jar.setAllCookies([])

    @can_load_page
    def evaluate(self, script):
        """Evaluates script in page frame.

        :param script: The script to evaluate.
        """
        return (self.main_frame.evaluateJavaScript("%s" % script),
            self._release_last_resources())

    def evaluate_js_file(self, path, encoding='utf-8'):
        """Evaluates javascript file at given path in current frame.
        Raises native IOException in case of invalid file.

        :param path: The path of the file.
        :param encoding: The file's encoding.
        """
        self.evaluate(codecs.open(path, encoding=encoding).read())

    def exists(self, selector):
        """Checks if element exists for given selector.

        :param string: The element selector.
        """
        return not self.main_frame.findFirstElement(selector).isNull()

    def exit(self):
        """Exits application and relateds."""
        if self.display:
            self.webview.close()
        Ghost._app.exit()
        del self.manager
开发者ID:v,项目名称:Ghost.py,代码行数:70,代码来源:ghost.py

示例8: Ghost

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]

#.........这里部分代码省略.........
        """Statement that tells Ghost how to deal with javascript confirm().

        :param confirm: A boolean to set confirmation.
        :param callable: A callable that returns a boolean for confirmation.
        """
        def __init__(self, confirm=True, callback=None):
            self.confirm = confirm
            self.callback = callback

        def __enter__(self):
            Ghost._confirm_expected = (self.confirm, self.callback)

        def __exit__(self, type, value, traceback):
            Ghost._confirm_expected = None

    @property
    def content(self, to_unicode=True):
        """Returns current frame HTML as a string.

        :param to_unicode: Whether to convert html to unicode or not
        """
        if to_unicode:
            return unicode(self.main_frame.toHtml())
        else:
            return self.main_frame.toHtml()

    @property
    def cookies(self):
        """Returns all cookies."""
        return self.cookie_jar.allCookies()

    def delete_cookies(self):
        """Deletes all cookies."""
        self.cookie_jar.setAllCookies([])

    def clear_alert_message(self):
        """Clears the alert message"""
        self._alert = None

    @can_load_page
    def evaluate(self, script):
        """Evaluates script in page frame.

        :param script: The script to evaluate.
        """
        return (self.main_frame.evaluateJavaScript("%s" % script),
            self._release_last_resources())

    def evaluate_js_file(self, path, encoding='utf-8'):
        """Evaluates javascript file at given path in current frame.
        Raises native IOException in case of invalid file.

        :param path: The path of the file.
        :param encoding: The file's encoding.
        """
        self.evaluate(codecs.open(path, encoding=encoding).read())

    def exists(self, selector):
        """Checks if element exists for given selector.

        :param string: The element selector.
        """
        return not self.main_frame.findFirstElement(selector).isNull()

    def exit(self):
        """Exits application and related."""
开发者ID:Awesoham,项目名称:Ghost.py,代码行数:70,代码来源:ghost.py

示例9: setAllCookies

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]
 def setAllCookies(self, cookieList):
     if not self.__read_only:
         QNetworkCookieJar.setAllCookies(self, cookieList)
         self.emit(SIGNAL('cookieJarUpdated()'))
开发者ID:Averroes,项目名称:raft,代码行数:6,代码来源:InMemoryCookieJar.py

示例10: GRobot

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]

#.........这里部分代码省略.........
            result.append(stream)

        return result


    @can_load_page
    def evaluate(self, script):
        """Evaluates script in page frame.

        @param script: The script to evaluate.
        """
        result = self.main_frame.evaluateJavaScript("%s" % script)
        # if isinstance(result,QString):
        #     result=unicode(result)
        return result

    def evaluate_js_file(self, path, encoding='utf-8'):
        """Evaluates javascript file at given path in current frame.
        Raises native IOException in case of invalid file.

        @param path: The path of the file.
        @param encoding: The file's encoding.
        """
        self.evaluate(codecs.open(path, encoding=encoding).read())

    def __del__(self):
        """Depend on the CG of Python.
        """
        self._exit()


    def delete_cookies(self):
        """Deletes all cookies."""
        self.cookie_jar.setAllCookies([])

    def exists(self, selector):
        """Checks if element exists for given selector.

        @param string: The element selector.
        """
        return not self.main_frame.findFirstElement(selector).isNull()


        #TODO: Still not work.

    #     def remove_css(self):
    #         """Remore the css,speed up page loading.
    #
    #         @return:
    #         """
    #
    #         return self.evaluate("""var targetelement="link";//determine element type to create nodelist from
    # var targetattr="href"//determine corresponding attribute to test for
    # var allsuspects=document.getElementsByTagName(targetelement)
    # for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
    # if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null )
    # allsuspects[i].parentNode.removeChild(allsuspects[i]); //remove element by calling parentNode.removeChild()
    # }
    #         """)


    def filter_resources(self, pattern):
        """Filter resources with pattern.

        @param pattern: Match pattern.
        @param resources:
开发者ID:waitingzeng,项目名称:GRobot,代码行数:70,代码来源:grobot.py

示例11: Ghost

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]

#.........这里部分代码省略.........
            evt.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1,
                false, false, false, false, 0, element);
            element.dispatchEvent(evt)
        """ % selector)

    class confirm:
        """Statement that tells Ghost how to deal with javascript confirm().

        :param confirm: A bollean that confirm.
        :param callable: A callable that returns a boolean for confirmation.
        """
        def __init__(self, confirm=True, callback=None):
            self.confirm = confirm
            self.callback = callback

        def __enter__(self):
            Ghost._confirm_expected = (self.confirm, self.callback)

        def __exit__(self, type, value, traceback):
            Ghost._confirm_expected = None

    @property
    def content(self):
        """Returns current frame HTML as a string."""
        return unicode(self.main_frame.toHtml())

    @property
    def cookies(self):
        """Returns all cookies."""
        return self.cookie_jar.allCookies()

    def delete_cookies(self):
        """Deletes all cookies."""
        self.cookie_jar.setAllCookies([])

    @can_load_page
    def evaluate(self, script):
        """Evaluates script in page frame.

        :param script: The script to evaluate.
        """
        return (self.main_frame.evaluateJavaScript("%s" % script),
            self._release_last_resources())

    def evaluate_js_file(self, path, encoding='utf-8'):
        """Evaluates javascript file at given path in current frame.
        Raises native IOException in case of invalid file.

        :param path: The path of the file.
        :param encoding: The file's encoding.
        """
        self.evaluate(codecs.open(path, encoding=encoding).read())

    def exists(self, selector):
        """Checks if element exists for given selector.

        :param string: The element selector.
        """
        return not self.main_frame.findFirstElement(selector).isNull()

    def exit(self):
        """Exits application and relateds."""
        if self.display:
            self.webview.close()
        Ghost._app.quit()
        del self.manager
开发者ID:mondras,项目名称:Ghost.py,代码行数:70,代码来源:ghost.py

示例12: ShoutCastForm

# 需要导入模块: from PyQt4.QtNetwork import QNetworkCookieJar [as 别名]
# 或者: from PyQt4.QtNetwork.QNetworkCookieJar import setAllCookies [as 别名]
class ShoutCastForm(PluginBase.PluginBase):
    '''Grab Shoutcast streams and save them as "bookmarks" - and play them on
       the currently selected server.

       General shoutcast information is not preserved between runs. Also, the
       shoutcast server/API is pretty lame so timeouts actually occur quite
       frequently.
    '''
    moduleName = '&Shoutcast'
    moduleIcon = "network-workgroup"

    def load(self):
        pass

    def event(self, event):
        if event.type() == QEvent.Paint:
            if not hasattr(self, 'webView'):
                self._load()
                self.event = super(ShoutCastForm, self).event
        return False

    def _load(self):
        self.cookie = QNetworkCookie('Settings', 'Player~others|Bandwidth~ALL|Codec~ALL')
        self.cookie.setDomain('.shoutcast.com')
        self.cookie.setExpirationDate(QDateTime())
        self.cookie.setPath('/')

        self.webView = QWebView(self)
        self.webPage = self.webView.page()
        self.cookiejar = QNetworkCookieJar()
        self.cookiejar.setAllCookies([self.cookie])
        self.webPage.networkAccessManager().setCookieJar(self.cookiejar)

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.webView)
        self.webView.load(QUrl(HOMEURL))
        self.webPage.setLinkDelegationPolicy(QWebPage.DelegateExternalLinks)
        self.connect(self.webPage, SIGNAL('linkClicked(const QUrl&)'), self._processLink)

    def _processLink(self, url):
        if url.host() == TUNEIN:
            self._playStation(url.toString())
        else:
            self.webView.load(url)
            self.webView.show()

    def _playStation(self, url):
        data = self._retreivePLS(url)
        adrlist = self._parsePLS(data)
        self.mpdclient.send('command_list_ok_begin')
        try:
            for address in adrlist:
                self.mpdclient.send('add', (address,))
        finally:
            self.mpdclient.send('command_list_end')

    def _retreivePLS(self, url):
        conn = httplib.HTTPConnection(TUNEIN)
        conn.request("GET", TUNEINFORMAT % url.split('=')[-1])
        resp = conn.getresponse()
        if resp.status == 200:
            return resp.read().split('\n')
        else:
            raise httplib.HTTPException('Got bad status code.')

    def _parsePLS(self, data):
        adrlist = []
        state = ''
        while data:
            line = data.pop(0)
            if state == '' and line == '[playlist]':
                state = 'playlist'
            elif state == 'playlist':
                if '=' in line:
                    key, value = line.split('=', 1)
                    if key.startswith('File'):
                        adrlist.append(value)
            else:
                raise httplib.HTTPException('Encountered error during parsing of the playlist.')
        return adrlist
开发者ID:Mvedrines,项目名称:Pythagora,代码行数:82,代码来源:ShoutcastForm.py


注:本文中的PyQt4.QtNetwork.QNetworkCookieJar.setAllCookies方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。