W0rMz000

Proxy Scraper and Checker in Python

Apr 29th, 2019 (edited)
999
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.88 KB | None | 0 0
  1. import urllib2, socket
  2. import urllib, urllib2
  3. import time, datetime
  4. import threading, Queue
  5. import re
  6. import StringIO, gzip
  7. import sys
  8. debug = False
  9.  
  10.  
  11. def bug(line):
  12.     if debug == True:
  13.         print "Debug:: " + line
  14.  
  15. def queueThread():
  16.     global proxyCount
  17.     ts = time.time()
  18.     dt = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d-%H-%M-%S')
  19.     print 'Saving...'
  20.     fout = open("scrape.txt", "w")
  21.  
  22.     while not workerQueue.empty():
  23.         fout.write(workerQueue.get() + "\n")
  24.         proxyCount+=1
  25.     fout.close()
  26.  
  27. def proxylist():
  28.     print "Grabbing..."
  29.     primary_url = "http://proxy-list.org/english/index.php?p="
  30.     urls = []
  31.     for i in range(1, 11):
  32.         urls.append(primary_url + str(i))
  33.  
  34.     for url in urls:
  35.         try:
  36.             bug("grabbing " + "'" + url + "'")
  37.             opener = urllib2.build_opener()
  38.             opener.addheaders = [('Host', 'www.proxylisty.com'),
  39.                                  ('Connection', 'keep-alive'),
  40.                                  ('Cache-Control', 'max-age=0'),
  41.                                  ('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
  42.                                  ('Upgrade-Insecure-Requests', '1'),
  43.                                  ('User-agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'),
  44.                                  ('Referer', 'https://www.google.co.za/'),
  45.                                  ('Accept-Encoding','gzip, deflate, sdch'),
  46.                                  ('Accept-Language','en-US,en;q=0.8')]
  47.  
  48.             response = opener.open(url, timeout=10)
  49.             compressedFile = StringIO.StringIO()
  50.             compressedFile.write(response.read())
  51.             compressedFile.seek(0)
  52.             decompessedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')
  53.             html = decompessedFile.read()
  54.  
  55.             templs = re.findall(r'<li class="proxy">([1-99999].*)?</li>', html)
  56.             for line in templs:
  57.                 workerQueue.put(line)
  58.                 bug("proxylist() " + line)
  59.  
  60.         except Exception, e:
  61.             if e.message == " ":
  62.                 bug(e.message)
  63.                 bug("Failed to grab " + "'" + url + "'")
  64.             else:
  65.                 bug("Failed to grab " + "'" + url + "'")
  66.        
  67.  
  68. def usproxy():
  69.    
  70.     templs = []
  71.     url = "http://www.us-proxy.org/"
  72.     try:
  73.         bug("grabbing " + "'" + url + "'")
  74.         opener = urllib2.build_opener()
  75.         opener.addheaders = [('Host', 'www.proxylisty.com'),
  76.                             ('Connection', 'keep-alive'),
  77.                             ('Cache-Control', 'max-age=0'),
  78.                             ('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
  79.                             ('Upgrade-Insecure-Requests', '1'),
  80.                             ('User-agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'),
  81.                             ('Referer', 'https://www.google.co.za/'),
  82.                             ('Accept-Encoding','gzip, deflate, sdch'),
  83.                             ('Accept-Language','en-US,en;q=0.8')]
  84.  
  85.         response = opener.open(url, timeout=10)
  86.         html = response.read()
  87.  
  88.         templs = re.findall(r'<tr><td>(.*?)</td><td>', html)
  89.         templs2 = re.findall(r'</td><td>[1-99999].*?</td><td>', html)
  90.  
  91.         for i in range(len(templs)):
  92.             temp = templs[i] + ":" + templs2[i].replace('</td><td>', '')
  93.             workerQueue.put(temp)
  94.             bug("usproxy() " + templs[i] + ":" + templs2[i].replace('</td><td>', ''))
  95.  
  96.     except Exception, e:
  97.         if e.message == " ":
  98.             bug(e.message)
  99.             bug("Failed to grab " + "'" + url + "'")
  100.         else:
  101.             bug("Failed to grab " + "'" + url + "'")
  102.  
  103.  
  104. def freeproxylist():
  105.  
  106.     url = "http://free-proxy-list.net/"
  107.     try:
  108.         bug("grabbing " + "'" + url + "'")
  109.         opener = urllib2.build_opener()
  110.         opener.addheaders = [('Host', 'www.proxylisty.com'),
  111.                             ('Connection', 'keep-alive'),
  112.                             ('Cache-Control', 'max-age=0'),
  113.                             ('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
  114.                             ('Upgrade-Insecure-Requests', '1'),
  115.                             ('User-agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'),
  116.                             ('Referer', 'https://www.google.co.za/'),
  117.                             ('Accept-Encoding','gzip, deflate, sdch'),
  118.                             ('Accept-Language','en-US,en;q=0.8')]
  119.  
  120.         response = opener.open(url, timeout=10)
  121.         html = response.read()
  122.  
  123.         templs = re.findall(r'<tr><td>(.*?)</td><td>', html)
  124.         templs2 = re.findall(r'</td><td>[1-99999].*?</td><td>', html)
  125.  
  126.         for i in range(len(templs)):
  127.             workerQueue.put(templs[i] + ":" + templs2[i].replace('</td><td>', ''))
  128.             bug("freeproxylist() " + templs[i] + ":" + templs2[i].replace('</td><td>', ''))
  129.  
  130.     except Exception, e:
  131.         if e.message == " ":
  132.             bug(e.message)
  133.             bug("Failed to grab " + "'" + url + "'")
  134.         else:
  135.             bug("Failed to grab " + "'" + url + "'")
  136.  
  137.  
  138. def coolproxy():
  139.    
  140.     primary_url = "http://www.cool-proxy.net/proxies/http_proxy_list/sort:score/direction:desc/page:"
  141.     urls = []
  142.     for i in range(1, 13):
  143.         urls.append(primary_url + str(i))
  144.  
  145.     for url in urls:
  146.         bug("grabbing " + "'" + url + "'")
  147.         try:
  148.             opener = urllib2.build_opener()
  149.             opener.addheaders = [('Host', 'www.proxylisty.com'),
  150.                                  ('Connection', 'keep-alive'),
  151.                                  ('Cache-Control', 'max-age=0'),
  152.                                  ('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
  153.                                  ('Upgrade-Insecure-Requests', '1'),
  154.                                  ('User-agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'),
  155.                                  ('Referer', 'https://www.google.co.za/'),
  156.                                  ('Accept-Encoding','gzip, deflate, sdch'),
  157.                                  ('Accept-Language','en-US,en;q=0.8')]
  158.  
  159.             response = opener.open(url, timeout=10)
  160.             compressedFile = StringIO.StringIO()
  161.             compressedFile.write(response.read())
  162.             compressedFile.seek(0)
  163.             decompessedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')
  164.             html = decompessedFile.read()
  165.  
  166.             templs = re.findall(r'str_rot13(.*?)</script>', html)
  167.             templs2 = re.findall(r'<td>[1-99999].*?</td>', html)
  168.  
  169.             for i in range(len(templs)):
  170.                 temp = templs[i].replace('("', '')#remove front of string
  171.                 temp = temp.replace('")))', '')#remove back of string
  172.                 temp = temp.decode('rot13').decode('base64')#decode from rot13 then from base64
  173.                 workerQueue.put(temp + templs2[i].replace('<td>', ':').replace('</td>', ''))
  174.                 bug("coolproxy() " + temp + templs2[i].replace('<td>', ':').replace('</td>', ''))
  175.        
  176.         except Exception, e:
  177.             if e.message == " ":
  178.                 bug(e.message)
  179.                 bug("Failed to grab " + "'" + url + "'")
  180.             else:
  181.                 bug("Failed to grab " + "'" + url + "'")
  182.  
  183.  
  184. def proxylisty():
  185.  
  186.     primary_url = "http://www.proxylisty.com/ip-proxylist-"
  187.     urls = []
  188.     for i in range(1, 68):
  189.         urls.append(primary_url + str(i))
  190.  
  191.     for url in urls:
  192.         try:
  193.             bug("grabbing " + "'" + url + "'")
  194.             opener = urllib2.build_opener()
  195.             opener.addheaders = [('Host', 'www.proxylisty.com'),
  196.                                  ('Connection', 'keep-alive'),
  197.                                  ('Cache-Control', 'max-age=0'),
  198.                                  ('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'),
  199.                                  ('Upgrade-Insecure-Requests', '1'),
  200.                                  ('User-agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'),
  201.                                  ('Referer', 'https://www.google.co.za/'),
  202.                                  ('Accept-Encoding','gzip, deflate, sdch'),
  203.                                  ('Accept-Language','en-US,en;q=0.8')]
  204.  
  205.             response = opener.open(url, timeout=10)
  206.             compressedFile = StringIO.StringIO()
  207.             compressedFile.write(response.read())
  208.             compressedFile.seek(0)
  209.             decompessedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')
  210.             html = decompessedFile.read()
  211.  
  212.             templs = re.findall(r'<tr>\n<td>(.*?)</td>', html)
  213.             templs2 = re.findall(r'com/port/(.*?)-ip-list', html)
  214.  
  215.             for i in range(len(templs)):
  216.                 workerQueue.put(templs[i] + ":" + templs2[i])
  217.                 bug("proxylisty() " + templs[i] + ":" + templs2[i])
  218.  
  219.         except Exception, e:
  220.             if e.message == " ":
  221.                 bug(e.message)
  222.                 bug("Failed to grab " + "'" + url + "'")
  223.             else:
  224.                 bug("Failed to grab " + "'" + url + "'")
  225.  
  226.  
  227. if __name__ == "__main__":
  228.    
  229.     print "Starting Proxy Scraper...\n"
  230.  
  231.     proxyCount = 0
  232.     workerQueue = Queue.Queue()
  233.     tQueueThread = threading.Thread(target=queueThread)
  234.     tQueueThread.deamon = True
  235.  
  236.  
  237.     tProxylist = threading.Thread(target=proxylist)
  238.     tProxylist.deamon = True
  239.  
  240.     tUsproxy = threading.Thread(target=usproxy)
  241.     tUsproxy.deamon = True
  242.  
  243.     tFreeproxylist = threading.Thread(target=freeproxylist)
  244.     tFreeproxylist.deamon = True
  245.  
  246.     tCoolproxy = threading.Thread(target=coolproxy)
  247.     tCoolproxy.deamon = True
  248.  
  249.  
  250.    
  251.     tProxylisty = threading.Thread(target=proxylisty)
  252.     tProxylisty.deamon = True
  253.  
  254.     tProxylist.start()
  255.     time.sleep(.500)
  256.     tUsproxy.start()
  257.     time.sleep(.500)
  258.     tFreeproxylist.start()
  259.     time.sleep(.500)
  260.     tCoolproxy.start()
  261.     time.sleep(.500)
  262.  
  263.     tProxylisty.start()
  264.  
  265.     time.sleep(2)
  266.     print "\nPlease wait..."
  267.  
  268.     tProxylist.join()
  269.     tUsproxy.join()
  270.     tFreeproxylist.join()
  271.     tCoolproxy.join()
  272.  
  273.     tProxylisty.join()
  274.  
  275.     if not workerQueue.empty():
  276.         tQueueThread.start()
  277.         tQueueThread.join()
  278.         print "Saved to file!\n"
  279.         print "Proxies found: " + str(proxyCount)
  280.     else:
  281.         print "Could not scrape any proxies!"
  282.  
  283. print "Checking..."
  284. time.sleep(2)
  285. text_file = open("Working.txt", "w")
  286. text_file.write("")
  287. text_file.close()
  288.  
  289. socket.setdefaulttimeout(.4)
  290. with open('scrape.txt') as f:
  291.     proxyList = f.readlines()
  292. # read the list of proxy IPs in proxyList
  293. #proxyList = ['172.30.1.1:8080', '172.30.3.3:8080'] # there are two sample proxy ip
  294.  
  295. def is_bad_proxy(pip):    
  296.     try:        
  297.         proxy_handler = urllib2.ProxyHandler({'http': pip})        
  298.         opener = urllib2.build_opener(proxy_handler)
  299.         opener.addheaders = [('User-agent', 'Mozilla/5.0')]
  300.         urllib2.install_opener(opener)        
  301.         req=urllib2.Request('http://www.google.com')  # change the url address here
  302.         sock=urllib2.urlopen(req)
  303.     except urllib2.HTTPError, e:        
  304.         #print 'Error code: ', e.code
  305.         return e.code
  306.     except Exception, detail:
  307.  
  308.         #print "ERROR:", detail
  309.         return 1
  310.     return 0
  311.  
  312. for item in proxyList:
  313.     if is_bad_proxy(item):
  314.         None
  315.     else:
  316.         print item
  317.     text_file = open("Working.txt", "a+")
  318.     text_file.write(item)
  319.     text_file.close()
Add Comment
Please, Sign In to add comment