---
title: "urllib2提交http post请求"
author: "finux"
date: "2010-10-17T16:06:44Z"
tags: []
categories: ["编程语言"]
slug: "urllib2-http-post"
draft: false
lastmod: "2010-10-17T16:06:44Z"
id: 786823
url: "https://finux.iteye.com/blog/786823"
---

urllib2实现是太强大，之前用c语言的curl库来实现post请求，觉着实太麻烦。

看了下urllib2的API文档，接着用它来模拟下xiami的登录，呵呵，就那么几行代码，简洁明了~

```
#!/usr/bin/python
#coding=utf-8

import urllib
import urllib2

def post(url, data):
	req = urllib2.Request(url)
	data = urllib.urlencode(data)
	#enable cookie
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
	response = opener.open(req, data)
	return response.read()

def main():
	posturl = "http://www.xiami.com/member/login"
	data = {'email':'myemail', 'password':'mypass', 'autologin':'1', 'submit':'登 录', 'type':''}
	print post(posturl, data)

if __name__ == '__main__':
	main()
```