# -*- coding: cp936 -*- #python 27 #xiaodeng #urllib2特点--urllib2.build_opener对象接口 import urllib2 import urllib #装载headers和data办法 def build(): #post headers={'User-Agent':'Mozilla/5.0','x-my-header':'my value'} data={'name':'xiaodeng','sex':1} req=urllib2.Request(url,headers=headers,data=urllib.urlencode(data)) #opener=urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)) #加上debuglevel=1,可以调试出发送的信息,这样可以直观的看到装载的效果 opener=urllib2.build_opener(urllib2.HTTPHandler()) s=opener.open(req) print s.read(100) s.close() if __name__=='__main__': build() ''' >>> send: 'POST /dengyg200891/ HTTP/1.1\r\nAccept-Encoding: identity\r\nContent-Length: 19\r\nX-My-Header: my value\r\nHost: www.cnblogs.com\r\nUser-Agent: Mozilla/5.0\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\nname=xiaodeng&sex=1' reply: 'HTTP/1.1 200 OK\r\n' header: Date: Wed, 30 Mar 2016 09:23:30 GMT header: Content-Type: text/html; charset=utf-8 header: Content-Length: 11881 header: Connection: close header: Vary: Accept-Encoding header: Cache-Control: private, max-age=10 header: Expires: Wed, 30 Mar 2016 09:23:40 GMT header: Last-Modified: Wed, 30 Mar 2016 09:23:30 GMT header: X-UA-Compatible: IE=10 <!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8"/> <title>Xiao|Deng - 博客园< >>> '''