urllib 模組使用簡例

來源:互聯網
上載者:User

標籤:bfd   pen   不能   splay   cto   分享   exp   urlencode   roc   

一、最簡單的使用

import urllib,urllib2response = urllib2.urlopen("https://www.baidu.com")print response.read()
View Code

二、構造Request對象

request = urllib2.Request("https://www.baidu.com")response = urllib2.urlopen(request)print response.read()
View Code

三、通過POST 、GET 方式請求

  POST

values = {‘username‘:‘test‘,‘passwrod‘:‘123‘}data = urllib.urlencode(values)print data    # username=test&passwrod=123request = urllib2.Request("https://www.baidu.com",data=data)response = urllib2.urlopen(request)print response.read()
View Code

  GET

value = {}value[‘username‘]=‘test‘value[‘password‘]=‘123‘data = urllib.urlencode(value)url = "https://www.baidu.com"+"?"+dataprint url    #   https://www.baidu.com?username=test&password=123request = urllib2.Request(url=url)response = urllib2.urlopen(request)print response.read()
View Code

四、quote,進行編碼

a = ‘哈哈‘A = urllib.quote(a)print AB = urllib.unquote(A)print B
View Code

  urlencode在 三 中的 GET 部分已有範例

五、佈建要求頭 header

url = "https://www.baidu.com"value = {"username":"test","password":"123"}data = urllib.urlencode(value)header = {        "User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0",        "Referer":"http://tieba.baidu.com/f?kw=%E4%BF%9D%E5%AE%9A&ie=utf-8&pn=50"    }request = urllib2.Request(url=url,data=data,headers=header)response = urllib2.urlopen(request)print response.read()
View Code

urlopen是urllib2.OpenerDirector的一個執行個體,一個opener ,一個特殊的預設的opener.因此,這個opener並不能總是滿足我們的需求,
這個時候,就需要我們自己構造自己的opener了。

源碼摘錄

_opener = Nonedef install_opener(opener):    global _opener    _opener = opener# ————————————————————————————————————————————————def urllopen():    """..."""    return opener.open(url, data, timeout)
View Code

六、設定代理

enable_proxy = Trueproxy_handler = urllib2.ProxyHandler({"http" : ‘http://some-proxy.com:8080‘})null_proxy = urllib2.ProxyHandler({})if enable_proxy:    opener = urllib2.build_opener(proxy_handler) #建立一個opener對象else:    opener = urllib2.build_opener(null_proxy)#urllib2.install_opener(opener)  #全域應用該openerrequest = urllib2.Request("https://www.baidu.com")response = opener.open(request)response = urllib2.urlopen(request)# print response.read()
View Code

七、操作cookie

import cookielib#建立一個CookieJar執行個體來儲存cookiecookie = cookielib.CookieJar()# 建立 Cookie 處理器handler = urllib2.HTTPCookieProcessor(cookie)#建立一個 openeropener = urllib2.build_opener(handler)# 用帶有cookie 處理器的opener 來請求urlresponse = opener.open("https://www.baidu.com")# for item in cookie:    print item     #<Cookie BIDUPSID=25441729620BF793C1BE08CA0B43C8D4 for .baidu.com/>    print ‘Name = ‘+item.name    #Name = BIDUPSID    print ‘Value = ‘+item.value    #Value = 25441729620BF793C1BE08CA0B43C8D4
View Code

八、儲存cookie到檔案

import cookielibfilename = "/home/an/savecookie.test"#建立一個 MozillaCookieJar 對象來儲存cookie ,稍後寫入對象cookie = cookielib.MozillaCookieJar(filename)# 建立 cookie 處理器handle = urllib2.HTTPCookieProcessor(cookie)#構建 handleropener = urllib2.build_opener(handle)response  = opener.open("http://www.baidu.com")#儲存cookie到檔案cookie.save(ignore_discard=True,ignore_expires=True)# ignore_discard 即使cookie被丟棄也儲存下來。# ignore_expires 如果該檔案中的cookie已存在,那麼就覆蓋
View Code

九、從檔案中取出cookie並使用

import cookielibcookie = cookielib.MozillaCookieJar()cookie.load("/home/an/savecookie.test",ignore_expires=True,ignore_discard=True)handler = urllib2.HTTPCookieProcessor(cookie)opener = urllib2.build_opener(handler)request = urllib2.Request("http://www.baidu.com")response = opener.open(request)print response.read()
View Code

 

urllib 模組使用簡例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.