Advertisement
stuppid_bot

WebBot source

Aug 28th, 2014
424
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.62 KB | None | 0 0
  1. #-*-coding:u8-*-
  2. __author__ = u'Сергей Снегирев <tz4678@gmail.com>'
  3.  
  4. import urllib
  5. import urllib2
  6. import cookielib
  7. import re
  8. import os
  9. import mimetypes
  10. import sys
  11. import random
  12.  
  13. def normalize_headers(headers):
  14.     ret = {}
  15.     for k, v in headers.items():
  16.         ret[k.lower().strip()] = v
  17.     return ret
  18.  
  19. def get_boundary(length=30):
  20.     chars = 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890'
  21.     ret = ''
  22.     while len(ret) < length:
  23.         ret += random.choice(chars)
  24.     return ret
  25.  
  26. class WebBot(object):
  27.     def __init__(self):
  28.         self.cookie_jar = cookielib.CookieJar()
  29.         self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie_jar))
  30.         self.default_headers = {'User-Agent': 'Mozilla/5.0'}
  31.  
  32.     def request(self, url, data=None, headers={}):
  33.         _headers = normalize_headers(self.default_headers)
  34.         _headers.update(normalize_headers(headers))
  35.         req = urllib2.Request(url, data, _headers)
  36.         res = self.opener.open(req)
  37.         return res
  38.  
  39.     def download(self, url, dst):
  40.         r = self.request(url)
  41.         fp = open(dst, 'wb')
  42.         while 1:
  43.             chunk = r.read(4096)
  44.             if not chunk:
  45.                 fp.close()
  46.                 break
  47.             fp.write(chunk)
  48.  
  49.     def fetch(self, url, data=None, headers={}):
  50.         try:
  51.             h = self.request(url, data, headers)
  52.         except urllib2.HTTPError as h:
  53.             pass
  54.         content = h.read()
  55.         ct = h.info().getheader('content-type')
  56.         try:
  57.             m = re.search(r'(?i)\bcharset\s*=\s*([^;]*)', ct)
  58.             content = content.decode(m.group(1))
  59.         except:
  60.             pass
  61.         return content
  62.  
  63.     def get(self, url, headers={}):
  64.         return self.fetch(url, None, headers)
  65.  
  66.     def post(self, url, parameters, headers={}):
  67.         data = urllib.urlencode(parameters)
  68.         return self.fetch(url, data, headers)
  69.      
  70.     def send_multipart(self, url, fields={}, files={}, headers={}):
  71.         lines = []
  72.         boundary = get_boundary()
  73.         headers = dict(headers)
  74.         headers['content-type'] = 'multipart/form-data; boundary=' + boundary
  75.         content_type = 'application/unknown'
  76.         for k, v in fields.items():
  77.             lines.extend([
  78.                 '--' + boundary,
  79.                 'Content-Disposition: form-data; name="' + k + '"',
  80.                 '',
  81.                 str(v)
  82.             ])
  83.         for k, v in files.items():
  84.             if re.match('(?i)https?://', v, re.I):
  85.                 v = str(v)
  86.                 r = self.request(v)
  87.                 content_type = r.info().get('content-type', content_type)
  88.                 data = r.read()
  89.             else:
  90.                 f = open(v, 'rb')
  91.                 data = f.read()
  92.                 f.close()
  93.                 ending = os.path.splitext(v)[1]
  94.                 content_type = mimetypes.types_map.get(ending, content_type)
  95.                 v = v.encode(sys.getfilesystemencoding())
  96.             lines.extend([
  97.                 '--' + boundary,
  98.                 'Content-Disposition: form-data; name="' + k +'"; filename="' + os.path.basename(v) + '"',
  99.                 'Content-Type: ' + content_type,
  100.                 '',
  101.                 data
  102.             ])
  103.         lines.extend([
  104.             '--' + boundary + '--',
  105.             ''
  106.         ])
  107.         payload = '\r\n'.join(lines)
  108.         return self.fetch(url, payload, headers)
  109.  
  110.     def del_cookie(self, domain=None, path=None, name=None):
  111.         self.cookie_jar.clear(domain, path, name)
  112.  
  113. if __name__ == '__main__':
  114.     wb = WebBot()
  115.     # do smth
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement