Untitled
By: a guest | Mar 17th, 2010 | Syntax:
Python | Size: 1.25 KB | Hits: 43 | Expires: Never
# -*- coding: utf-8 -*-
import urllib2
import sys, os, cookielib
def post(url, data, return_new_url=False, referer = '', ctype='text/plain'):
COOKIEFILE = 'cookies.lwp'
cj = cookielib.LWPCookieJar(COOKIEFILE)
if os.path.isfile(COOKIEFILE):
cj.load(COOKIEFILE)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
user_agent = 'Monthy-Mozilla/4.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent, 'Referer' :referer, 'Content-type':ctype}
req = urllib2.Request(url, data, headers)
try:
urlh = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print 'Error code: ', e.code, 'for ', url
return False
except urllib2.URLError, e:
print 'We failed to reach a server - ' + url
print 'Reason: ', e.reason
return False
data = urlh.read()
urlh.close()
cj.save(COOKIEFILE)
for index, cookie in enumerate(cj):
print index, ' : ', cookie
if return_new_url:
return data, urlh.geturl()
return data
if __name__ == "__main__":
import urllib
a = post("http://online.bilets.org/", None)
a = post("http://yandex.ru/", None)