当前位置:首页 >> 脚本专栏

Python get获取页面cookie代码实例

在Python中通过GET来获取页面的COOKIE是非常简单的事情,下面的代码实例演示了如何利用Python 获取COOKIE内容

#! /usr/bin/env python
#coding=utf-8
# -*-coding:utf-8 -*-
#encoding=utf-8

import urllib
import urllib2
import httplib

cj=''
header={'Host':'218.94.26.135',
    'Accept-Language':'zh-CN',
    'Connection':'Keep-Alive',
    'Accept-Encoding':'gzip,deflate',
    'Accept':'text/html, application/xhtml+xml, */*',
    'User-Agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.71 Chrome/28.0.1500.71 Safari/537.36'
    }

con=httplib.HTTPConnection('218.94.26.135')            #建立请求:218.94.26.135/casequery/KT_index.jsp?fydm=320100%20A00
con.request(method='GET',url='/casequery/KT_index.jsp?fydm=320100%20A00',headers=header)
res=con.getresponse()
res.read()                              #调用read函数以后,才能获取content。
con.close()

if res.getheader('Set-Cookie')!=None:                #判断是否存在Set-Cookie,有的话,将cookie保存起来
  cj=res.getheader('Set-Cookie').split(';')[0]
  print cj
else:
  print 'got no cookie'

代码很简单,只需要简单的几个命令即可获取