使用Python中的cookielib類比登入網站

來源:互聯網
上載者:User
前面簡單提到了 Python 類比登入的程式,但是沒寫清楚,這裡再補上一個帶注釋的 Python 類比登入的樣本程式。簡單說一下流程:先用cookielib擷取cookie,再用擷取到的cookie,進入需要登入的網站。

 # -*- coding: utf-8 -*- # !/usr/bin/python  import urllib2 import urllib import cookielib import re  auth_url = 'http://www.nowamagic.net/' home_url = 'http://www.nowamagic.net/'; # 登陸使用者名稱和密碼 data={   "username":"nowamagic",   "password":"pass" } # urllib進行編碼 post_data=urllib.urlencode(data) # 發送頭資訊 headers ={   "Host":"www.nowamagic.net", "Referer": "http://www.nowamagic.net" } # 初始化一個CookieJar來處理Cookie cookieJar=cookielib.CookieJar() # 執行個體化一個全域opener opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar)) # 擷取cookie req=urllib2.Request(auth_url,post_data,headers) result = opener.open(req) # 訪問首頁 自動帶著cookie資訊 result = opener.open(home_url) # 顯示結果 print result.read()

再附帶幾個樣本程式:

1. 使用已有的cookie訪問網站

import cookielib, urllib2  ckjar = cookielib.MozillaCookieJar(os.path.join('C:\Documents and Settings\tom\Application Data\Mozilla\Firefox\Profiles\h5m61j1i.default', 'cookies.txt'))  req = urllib2.Request(url, postdata, header)  req.add_header('User-Agent', \   'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')  opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(ckjar) )  f = opener.open(req) htm = f.read() f.close()

2. 訪問網站獲得cookie,並把獲得的cookie儲存在cookie檔案中

 import cookielib, urllib2  req = urllib2.Request(url, postdata, header) req.add_header('User-Agent', \   'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')  ckjar = cookielib.MozillaCookieJar(filename) ckproc = urllib2.HTTPCookieProcessor(ckjar)  opener = urllib2.build_opener(ckproc)  f = opener.open(req) htm = f.read() f.close()  ckjar.save(ignore_discard=True, ignore_expires=True)

3. 使用指定的參數產生cookie,並用這個cookie訪問網站

 import cookielib, urllib2  cookiejar = cookielib.CookieJar() urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar)) values = {'redirect':", 'email':'abc@abc.com',      'password':'password', 'rememberme':", 'submit':'OK, Let Me In!'} data = urllib.urlencode(values)  request = urllib2.Request(url, data) url = urlOpener.open(request) print url.info() page = url.read()  request = urllib2.Request(url) url = urlOpener.open(request) page = url.read() print page
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.