Python模仿POST提交HTTP資料以及使用Cookie值

來源:互聯網
上載者:User


方法一


如果不使用Cookie, 發送HTTP POST非常簡單:

 代碼如下 複製代碼

import urllib2, urllib

data = {'name' : 'www', 'password' : '123456'}
f = urllib2.urlopen(
        url     = 'http://www.111cn.net/',
        data    = urllib.urlencode(data)
  )
print f.read()

當使用Cookie時, 代碼變得有些複雜:

 代碼如下 複製代碼

import urllib2

cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)

f = opener.open('http://www.xxxx.net/?act=login&name=user01')

data = '<root>Hello</root>'
request = urllib2.Request(
        url     = 'http://www.xxxx.net/?act=send',
        headers = {'Content-Type' : 'text/xml'},
        data    = data)

opener.open(request)

第一次 open() 是進行登入. 伺服器返回的 Cookie 被自動儲存在 cookies 中, 被用在後來的請求.

第二次 open() 用 POST 方法向伺服器發送了 Content-Type=text/xml 的資料. 如果你不建立一個 Request, 而是直接使用 urlopen() 方法, Python 強制把 Content-Type 改為 application/x-www-form-urlencoded.


方法二


用urllib2庫,帶Cookie請求URL頁面


例1:

 代碼如下 複製代碼

import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

例2:

 代碼如下 複製代碼
import urllib2
import urllib
from cookielib import CookieJar
 
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("https://page.com/login.php", data_encoded)
content = response.read()

聯繫我們

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