zoukankan      html  css  js  c++  java
  • Python urllib简单使用

    Python的urllib和urllib2模块都做与请求URL相关的操作。

    它们最显著的差异为:

    urllib2可以接受一个Request对象,并以此可以来设置一个URL的headers,但是urllib只接收一个URL。

    urllib模块可以提供进行urlencode的方法,该方法用于GET查询字符串的生成,urllib2的不具有这样的功能.

    python 2.7.x提供了urllib与urllib2,鉴于上述异同两个库通常搭配使用。

    urlopen

    urllib2.urlopen(url, *data, *timeout)

    urlopen方法是urllib2模块最常用的方法,用于访问发送某一请求。

    url参数可以是一个字符串url或者是一个Request对象。

    可选参数timeout用于设置超时时间,以秒为单位。

    如果没有指定,将使用设置的全局默认timeout值。

    urlopen使用默认opener进行访问, 为阻塞式IO.

    如果请求成功,函数将返回响应。

    在data为None时默认用GET方法:

    import urllib2
    response = urllib2.urlopen('http://python.org/')
    html = response.read()
    print(html)

    使用POST发送参数前需要先将参数编码:

    import urllib
    import urllib2
    
    values = {
        'action': 'sign-in',
        'username': 'finley',
        'password': '1234'
    }
    values = urllib.urlencode(values)
    response = urllib2.urlopen('http://127.0.0.1:8080/game', values)
    print(response.read())

    urllib.urlencode不能直接进行Unicode编码,需要先进行转码:

    urllib.urlencode (u'bl'.encode('utf-8'))

    qutoe与urlencode均可以进行编码,区别在于quote的空格由%20替代而urlencode的空格由+替代。

    Request

    使用Request对象可以设置更多请求参数:

    Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

    • url: url字符串

    • data:额外发送的数据

    在data为None时默认用GET方法提交,有参数时默认用POST方法提交

    示例:

    import urllib
    import urllib2
    url = 'http://127.0.0.1:8080/game'
    values = {
        'action': 'sign-in',
        'username': 'finley',
        'password': '1234'
    }
    data = urllib.urlencode(values)
    request = urllib2.Request(url, data)
    response = urllib2.urlopen(request)
    html = response.read()

    cookie

    为了使用cookie我们需要一个opener对象来维护cookiejar.

    class BaseDriver:
        def __init__(self):
            self.opener = None
            self.cookiejar = None
            self.initOpener()
    
        def initOpener(self):
            self.cookiejar = cookielib.CookieJar()
            self.opener = urllib2.build_opener(
                urllib2.HTTPCookieProcessor(self.cookiejar)
            )
    
        def get_cookie(self):
            for cookie in self.cookiejar:
                if cookie.name == 'csrftoken':
                    return cookie.value
            return None
    
        def doRequest(self, action, values):
            data = urllib.urlencode(values)
            request = urllib2.Request(url, data)
            return self.opener.open(request)

    参考资料:

    urllib与urllib2的学习总结(python2.7.X)

    Python爬虫入门六之Cookie的使用

    urllib module doc

    urllib2 module doc

  • 相关阅读:
    html
    头部标签
    ajax
    分辨率
    js 运动基础
    js DOM
    js定时器
    js数组
    js基础
    例子:js简易日历
  • 原文地址:https://www.cnblogs.com/fungitive/p/9136171.html
Copyright © 2011-2022 走看看