Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Mar 17th, 2010 | Syntax: Python | Size: 1.25 KB | Hits: 43 | Expires: Never
Copy text to clipboard
  1. # -*- coding: utf-8 -*-
  2.  
  3. import urllib2
  4. import sys, os, cookielib
  5.  
  6. def post(url, data, return_new_url=False, referer = '', ctype='text/plain'):
  7.     COOKIEFILE = 'cookies.lwp'
  8.     cj = cookielib.LWPCookieJar(COOKIEFILE)
  9.     if os.path.isfile(COOKIEFILE):
  10.         cj.load(COOKIEFILE)
  11.  
  12.     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  13.     urllib2.install_opener(opener)
  14.     user_agent = 'Monthy-Mozilla/4.1 (compatible; MSIE 5.5; Windows NT)'
  15.     headers = { 'User-Agent' : user_agent,  'Referer' :referer, 'Content-type':ctype}
  16.     req = urllib2.Request(url, data, headers)
  17.     try:
  18.         urlh = urllib2.urlopen(req)
  19.     except urllib2.HTTPError, e:
  20.         print 'Error code: ', e.code, 'for ', url
  21.         return False
  22.     except urllib2.URLError, e:
  23.         print 'We failed to reach a server - ' + url
  24.         print 'Reason: ', e.reason
  25.         return False
  26.  
  27.     data = urlh.read()
  28.     urlh.close()
  29.     cj.save(COOKIEFILE)
  30.    
  31.     for index, cookie in enumerate(cj):
  32.         print index, '  :  ', cookie
  33.  
  34.     if return_new_url:
  35.         return data, urlh.geturl()
  36.     return data
  37.  
  38. if __name__ == "__main__":
  39.  
  40.     import urllib
  41.     a = post("http://online.bilets.org/", None)
  42.     a = post("http://yandex.ru/", None)