ITeye博客

urllib2提交http post请求

finux · 2010-10-17 16:06 · Python · 编程语言 · Markdown

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()

评论(2)

  1. #2 楼 · finux · 2010-10-18 22:40

    greatghoul writes:

    这里如何将登陆后的Cookie保存下来,这样才可以请求其它需要登陆才能访问的页面。

    可以先把Cookie保存起来,然后下次请求时使用即可,试试下面的代码:

    
    #!/usr/bin/python
    #coding=utf-8
    
    import urllib
    import urllib2
    import cookielib
    
    def post(url, data):
    	req = urllib2.Request(url)
    	data = urllib.urlencode(data)
    	#enable cookie
    	cookiefile = "cookiefile"
    	cookieJar = cookielib.MozillaCookieJar(cookiefile)
    	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar));
    	response = opener.open(req, data)
    	cookieJar.save()
    	#print response.read()
    
    	#second http request use cookie
    	cookieJar = cookielib.MozillaCookieJar(cookiefile)
    	cookieJar.load()
    	url = "http://www.xiami.com"
    	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
    	response = opener.open(url)
    	print response.read()
    
    def main():
    	posturl = "http://www.xiami.com/member/login"
    	data = {'email':'myemail', 'password':'mypass', 'autologin':'1', 'submit':'登 录', 'type':''}
    	#print post(posturl, data)
    	post(posturl, data)
    
    if __name__ == '__main__':
    	main()
    
    
    
    
  2. #1 楼 · greatghoul · 2010-10-18 13:36

    这里如何将登陆后的Cookie保存下来,这样才可以请求其它需要登陆才能访问的页面。

评论功能维护中,当前仅展示历史评论。