當前位置: 首頁>>代碼示例>>Python>>正文


Python urllib2.request方法代碼示例

本文整理匯總了Python中urllib2.request方法的典型用法代碼示例。如果您正苦於以下問題:Python urllib2.request方法的具體用法?Python urllib2.request怎麽用?Python urllib2.request使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在urllib2的用法示例。


在下文中一共展示了urllib2.request方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _make_request

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def _make_request(self, opener, request, timeout=None):
        """Make the API call and return the response. This is separated into
           it's own function, so we can mock it easily for testing.

        :param opener:
        :type opener:
        :param request: url payload to request
        :type request: urllib.Request object
        :param timeout: timeout value or None
        :type timeout: float
        :return: urllib response
        """
        timeout = timeout or self.timeout
        try:
            return opener.open(request, timeout=timeout)
        except HTTPError as err:
            exc = handle_error(err)
            return exc 
開發者ID:d6t,項目名稱:d6tpipe,代碼行數:20,代碼來源:client.py

示例2: _get_data

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def _get_data(url):
    """Helper function to get data over http or from a local file"""
    if url.startswith('http://'):
        # Try Python 2, use Python 3 on exception
        try:
            resp = urllib.urlopen(url)
            encoding = resp.headers.dict.get('content-encoding', 'plain')
        except AttributeError:
            resp = urllib.request.urlopen(url)
            encoding = resp.headers.get('content-encoding', 'plain')
        data = resp.read()
        if encoding == 'plain':
            pass
        elif encoding == 'gzip':
            data = StringIO(data)
            data = gzip.GzipFile(fileobj=data).read()
        else:
            raise RuntimeError('unknown encoding')
    else:
        with open(url, 'r') as fid:
            data = fid.read()
        fid.close()

    return data 
開發者ID:sklearn-theano,項目名稱:sklearn-theano,代碼行數:26,代碼來源:gen_rst.py

示例3: _get_data

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def _get_data(url):
    """Helper function to get data over http or from a local file"""
    if url.startswith('http://'):
        # Try Python 2, use Python 3 on exception
        try:
            resp = urllib.urlopen(url)
            encoding = resp.headers.dict.get('content-encoding', 'plain')
        except AttributeError:
            resp = urllib.request.urlopen(url)
            encoding = resp.headers.get('content-encoding', 'plain')
        data = resp.read()
        if encoding == 'plain':
            pass
        elif encoding == 'gzip':
            data = StringIO(data)
            data = gzip.GzipFile(fileobj=data).read()
        else:
            raise RuntimeError('unknown encoding')
    else:
        with open(url, 'r') as fid:
            data = fid.read()

    return data 
開發者ID:cokelaer,項目名稱:spectrum,代碼行數:25,代碼來源:docs_resolv.py

示例4: make_request

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def make_request(self,
                     method,
                     request_body=None,
                     query_params=None,
                     request_headers=None):
        method = method.upper()
        if request_headers:
            self._set_headers(request_headers)
            request_body = json.dumps(request_body) if request_body else None
            query_params = query_params if query_params else None
            opener = urllib.build_opener()
            request = urllib.Request(self._build_url(query_params),
                                     data=request_body)
            for key, value in self.request_headers.iteritems():
                request.add_header(key, value)
            request.get_method = lambda: method
            self._response = opener.open(request)
            self._set_response(self._response)
            self._reset() 
開發者ID:sendgrid,項目名稱:python-http-client,代碼行數:21,代碼來源:profile.py

示例5: _update_headers

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def _update_headers(self, request_headers):
        """Update the headers for the request

        :param request_headers: headers to set for the API call
        :type request_headers: dictionary
        :return: dictionary
        """
        self.request_headers.update(request_headers) 
開發者ID:d6t,項目名稱:d6tpipe,代碼行數:10,代碼來源:client.py

示例6: GET

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def GET(path):
    url = getURL()
    opener = getOpener()
    request = urllib.Request(url)
    response = opener.open(request)
    setValues(response) 
開發者ID:f-prime,項目名稱:HTTPLang,代碼行數:8,代碼來源:make_request.py

示例7: POST

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def POST(path):
    url = getURL()
    opener = getOpener()
    request = urllib.Request(url, GLOBALS['POSTDATA'])
    response = opener.open(request)
    setValues(response) 
開發者ID:f-prime,項目名稱:HTTPLang,代碼行數:8,代碼來源:make_request.py

示例8: extractArticlePublishedDate

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def extractArticlePublishedDate(articleLink, html = None):

    print("Extracting date from " + articleLink)

    articleDate = None

    try:
        articleDate = _extractFromURL(articleLink)

        if html is None:
            request = urllib.Request(articleLink)
            # Using a browser user agent, decreases the change of sites blocking this request - just a suggestion
            # request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
            html = urllib.build_opener().open(request).read()

        parsedHTML = BeautifulSoup(html,"lxml")

        possibleDate = _extractFromLDJson(parsedHTML)
        if possibleDate is None:
            possibleDate = _extractFromMeta(parsedHTML)
        if possibleDate is None:
            possibleDate = _extractFromHTMLTag(parsedHTML)


        articleDate = possibleDate

    except Exception as e:
        print("Exception in extractArticlePublishedDate for " + articleLink)
        print(e.args)   

    return articleDate 
開發者ID:Webhose,項目名稱:article-date-extractor,代碼行數:33,代碼來源:__init__.py

示例9: _make_request

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def _make_request(self, opener, request, timeout=None):
        if 200 <= self.response_code < 299:  # if successful code
            return MockResponse(self.response_code)
        else:
            raise handle_error(MockException(self.response_code)) 
開發者ID:sendgrid,項目名稱:python-http-client,代碼行數:7,代碼來源:test_unit.py

示例10: test__urllib_headers

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def test__urllib_headers(self, maker):
        self.client._update_headers({'X-test': 'Test'})
        self.client.get()
        request = maker.call_args[0][1]
        self.assertIn('X-test', request.headers) 
開發者ID:sendgrid,項目名稱:python-http-client,代碼行數:7,代碼來源:test_unit.py

示例11: test__urllib_method

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def test__urllib_method(self, maker):
        self.client.delete()
        request = maker.call_args[0][1]
        self.assertEqual(request.get_method(), 'DELETE') 
開發者ID:sendgrid,項目名稱:python-http-client,代碼行數:6,代碼來源:test_unit.py

示例12: download_file

# 需要導入模塊: import urllib2 [as 別名]
# 或者: from urllib2 import request [as 別名]
def download_file():
    big_file_url = "http://www.python.org/ftp/python/3.3.2/Python-3.3.2.tgz"

    # Download the file
    if sys.version_info[0] == 3:
        f = urllib.request.urlopen(big_file_url)
    else:
        f = urllib.urlopen(big_file_url)

    # Get the total length of the file
    scale = int(f.headers["content-length"])
    chunk_size = 500

    bar = CustomProgressBar(length=50,
                            left_limit='[',
                            right_limit=']',
                            head_repr=None,
                            empty_repr=' ',
                            filled_repr='|',
                            start=0,
                            scale_start=0,
                            scale_end=scale)

    print("Downloading a big txt file: ")

    print_flag = 0
    # Load all the data chunk by chunk
    while not bar.completed():
        f.read(chunk_size)
        bar.increase(chunk_size)

        # Don't print always
        if print_flag == 100:
            bar.show_progress_bar()
            print_flag = 0
        else:
            print_flag += 1

    bar.show_progress_bar()
    print("")
    print("Finished :)") 
開發者ID:soarpenguin,項目名稱:python-scripts,代碼行數:43,代碼來源:examples.py


注:本文中的urllib2.request方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。