Skip to content

Instantly share code, notes, and snippets.

@taojy123
Last active August 29, 2015 14:11
Show Gist options
  • Save taojy123/2f2ab8d4a71db4400f58 to your computer and use it in GitHub Desktop.
Save taojy123/2f2ab8d4a71db4400f58 to your computer and use it in GitHub Desktop.
Python 模拟POST发包,并且保存cookie,可用于需要登录的操作
#coding=utf8
import cookielib
import urllib2, urllib
import time
import re
import traceback
import time
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.ProxyHandler({'http':"10.239.120.37:911"}))
opener.addheaders = [
('User-agent', 'Mozilla/5.0 (Windows NT 5.2) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1'),
]
def get_page(url, data=None):
resp = None
n = 0
while n < 3:
n = n + 1
try:
resp = opener.open(url, data, timeout=5)
page = resp.read()
return page
except:
#traceback.print_exc()
time.sleep(2)
print "Try after 2 seconds ..."
continue
raise Exception("Get page failed")
url = "http://www.baidu.com/login..."
formData = urllib.urlencode({'username' : "abc",
'password' : "123",
})
p = get_page(url, formData)
print p
url2 = "http://www.baidu.com/"
p = get_page(url2)
print p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment