您的位置:首页 > 理论基础 > 计算机网络

随笔——python截取http请求报文响应头

sandikast 2014-05-29 09:32 25 查看
Request.add_header——作用是在http报文中加入条目

page.info().getheader("item")——用来获取http响应头中的item条目内容

import urllib2
import urllib
from types import *
import hashlib

req = urllib2.Request('http://script2.iscc.org.cn/web07_e3a95260b7271954aa59460c134cde7e/')
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.0)')
req.add_header('Host', 'script2.iscc.org.cn')
req.add_header('Connection', 'keep-alive')
req.add_header('Referer', 'http://www.iscc.org.cn/challenges/2014/web/web06/')

urllib2.socket.setdefaulttimeout(10)
page = urllib2.urlopen(req)
password=page.info().getheader("PassWord")
cookie=page.info().getheader("Set-Cookie")
cookie=cookie[0:45]
print password
print cookie
data = page.read()
hash_value = hashlib.md5(password).hexdigest().upper()
print hash_value
print len(data)

test_data = 'pwd='+hash_value+'&Submit=%E6%8F%90%E4%BA%A4'
print test_data

requrl = "http://script2.iscc.org.cn/web07_e3a95260b7271954aa59460c134cde7e/index.asp?action=Check"
req = urllib2.Request(url = requrl,data =test_data)
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.0)')
req.add_header('Cookie', cookie)
req.add_header('Referer', ' http://script2.iscc.org.cn/web07_e3a95260b7271954aa59460c134cde7e/') res_data = urllib2.urlopen(req)
res = res_data.read()
f = open("C:\\1.html", 'wb')
f.write(res)
f.close()
print res
标签: