# your code goes here

import re,urllib,cookielib,urllib2,time,mimetools,cfscrape,sys,os

tred=sys.argv[1]
tredname=re.findall(r'/([^/]+?)$',tred)[0]
tredname=re.sub(r'\.html','',tredname)
prefSos=re.findall(r'^(.+?)/res/',tred)[0]

myHeaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1'),('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')]
cj=cookielib.CookieJar()
opener1=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener1.addheaders=myHeaders
urllib2.install_opener(opener1)

scraper = cfscrape.create_scraper(js_engine="Node")  # returns a CloudflareScraper instance
# Or: scraper = cfscrape.CloudflareScraper()  # CloudflareScraper inherits from requests.Session
data=scraper.get(tred).content

pics=re.findall(r'href="\.\.(\/src[^"]+?)"',data,re.U+re.S)

if pics:
  if not os.path.exists('./'+tredname):
    os.makedirs('./'+tredname)

for pic in pics:
  fn='./'+tredname+'/'+re.findall(r'/([^/]+?)$',pic)[0]
  if not os.path.exists(fn):
    print 'processing %s '%fn,
    imagedata=scraper.get(prefSos+pic).content
    f1=open(fn,'wb');f1.write(imagedata);f1.close()
    print ' done.'

print 'all done.'

