getFreeProxy.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. """
  4. -------------------------------------------------
  5. File Name: GetFreeProxy.py
  6. Description : 抓取免费代理
  7. Author : JHao
  8. date: 2016/11/25
  9. -------------------------------------------------
  10. Change Activity:
  11. 2016/11/25:
  12. -------------------------------------------------
  13. """
  14. import re
  15. import sys
  16. import requests
  17. try:
  18. from importlib import reload # py3 实际不会实用,只是为了不显示语法错误
  19. except:
  20. reload(sys)
  21. sys.setdefaultencoding('utf-8')
  22. sys.path.append('..')
  23. from Util.utilFunction import robustCrawl, getHtmlTree
  24. from Util.WebRequest import WebRequest
  25. # for debug to disable insecureWarning
  26. requests.packages.urllib3.disable_warnings()
  27. """
  28. 66ip.cn
  29. data5u.com
  30. xicidaili.com
  31. goubanjia.com
  32. xdaili.cn
  33. kuaidaili.com
  34. cn-proxy.com
  35. proxy-list.org
  36. www.mimiip.com to do
  37. """
  38. class GetFreeProxy(object):
  39. """
  40. proxy getter
  41. """
  42. def __init__(self):
  43. pass
  44. @staticmethod
  45. def freeProxyFirst(page=10):
  46. """
  47. 抓取无忧代理 http://www.data5u.com/
  48. 几乎没有能用的
  49. :param page: 页数
  50. :return:
  51. """
  52. url_list = [
  53. 'http://www.data5u.com/',
  54. 'http://www.data5u.com/free/gngn/index.shtml',
  55. 'http://www.data5u.com/free/gnpt/index.shtml'
  56. ]
  57. for url in url_list:
  58. html_tree = getHtmlTree(url)
  59. ul_list = html_tree.xpath('//ul[@class="l2"]')
  60. for ul in ul_list:
  61. try:
  62. yield ':'.join(ul.xpath('.//li/text()')[0:2])
  63. except Exception as e:
  64. print(e)
  65. @staticmethod
  66. def deprecatedFreeProxySecond(proxy_number=100):
  67. """
  68. 抓取代理66 http://www.66ip.cn/
  69. :param proxy_number: 代理数量
  70. :return:
  71. """
  72. url = "http://www.66ip.cn/mo.php?sxb=&tqsl={}&port=&export=&ktip=&sxa=&submit=%CC%E1++%C8%A1&textarea=".format(
  73. proxy_number)
  74. request = WebRequest()
  75. html = request.get(url).text
  76. for proxy in re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}', html):
  77. yield proxy
  78. @staticmethod
  79. def freeProxySecond(area=33):
  80. """
  81. 修改抓取代理66 http://www.66ip.cn/
  82. :param page:抓取代理页数,page=1北京代理页,page=2上海代理页......
  83. :return:
  84. """
  85. if area > 33:
  86. page = 33
  87. for area_index in range(1, area + 1):
  88. page_count = 5
  89. for i in range(1, page_count + 1):
  90. url = "http://www.66ip.cn/areaindex_{}/{}.html".format(area_index, i)
  91. html_tree = getHtmlTree(url)
  92. tr_list = html_tree.xpath("//*[@id='footer']/div/table/tr[position()>1]")
  93. if len(tr_list) == 0:
  94. continue
  95. for tr in tr_list:
  96. yield tr.xpath("./td[1]/text()")[0] + ":" + tr.xpath("./td[2]/text()")[0]
  97. break
  98. '''
  99. 不能用了
  100. @staticmethod
  101. def freeProxyThird(days=1):
  102. """
  103. 抓取ip181 http://www.ip181.com/
  104. :param days:
  105. :return:
  106. """
  107. url = 'http://www.ip181.com/'
  108. html_tree = getHtmlTree(url)
  109. try:
  110. tr_list = html_tree.xpath('//tr')[1:]
  111. for tr in tr_list:
  112. yield ':'.join(tr.xpath('./td/text()')[0:2])
  113. except Exception as e:
  114. pass
  115. '''
  116. @staticmethod
  117. def freeProxyFourth(page_count=2):
  118. """
  119. 抓取西刺代理 http://api.xicidaili.com/free2016.txt
  120. :return:
  121. """
  122. url_list = [
  123. 'http://www.xicidaili.com/nn/', # 高匿
  124. 'http://www.xicidaili.com/nt/', # 透明
  125. ]
  126. for each_url in url_list:
  127. for i in range(1, page_count + 1):
  128. page_url = each_url + str(i)
  129. tree = getHtmlTree(page_url)
  130. proxy_list = tree.xpath('.//table[@id="ip_list"]//tr[position()>1]')
  131. for proxy in proxy_list:
  132. try:
  133. yield ':'.join(proxy.xpath('./td/text()')[0:2])
  134. except Exception as e:
  135. pass
  136. @staticmethod
  137. def freeProxyFifth():
  138. """
  139. 抓取guobanjia http://www.goubanjia.com/
  140. :return:
  141. """
  142. url = "http://www.goubanjia.com/"
  143. tree = getHtmlTree(url)
  144. proxy_list = tree.xpath('//td[@class="ip"]')
  145. # 此网站有隐藏的数字干扰,或抓取到多余的数字或.符号
  146. # 需要过滤掉<p style="display:none;">的内容
  147. xpath_str = """.//*[not(contains(@style, 'display: none'))
  148. and not(contains(@style, 'display:none'))
  149. and not(contains(@class, 'port'))
  150. ]/text()
  151. """
  152. for each_proxy in proxy_list:
  153. try:
  154. # :符号裸放在td下,其他放在div span p中,先分割找出ip,再找port
  155. ip_addr = ''.join(each_proxy.xpath(xpath_str))
  156. port = each_proxy.xpath(".//span[contains(@class, 'port')]/text()")[0]
  157. yield '{}:{}'.format(ip_addr, port)
  158. except Exception as e:
  159. pass
  160. @staticmethod
  161. def freeProxySixth():
  162. """
  163. 抓取讯代理免费proxy http://www.xdaili.cn/ipagent/freeip/getFreeIps?page=1&rows=10
  164. :return:
  165. """
  166. url = 'http://www.xdaili.cn/ipagent/freeip/getFreeIps?page=1&rows=10'
  167. request = WebRequest()
  168. try:
  169. res = request.get(url).json()
  170. for row in res['RESULT']['rows']:
  171. yield '{}:{}'.format(row['ip'], row['port'])
  172. except Exception as e:
  173. pass
  174. @staticmethod
  175. def freeProxySeventh():
  176. """
  177. 快代理免费https://www.kuaidaili.com/free/inha/1/
  178. """
  179. url_list = [
  180. 'https://www.kuaidaili.com/free/inha/{page}/',
  181. 'https://www.kuaidaili.com/free/intr/{page}/'
  182. ]
  183. for url in url_list:
  184. for page in range(1, 5):
  185. page_url = url.format(page=page)
  186. tree = getHtmlTree(page_url)
  187. proxy_list = tree.xpath('.//table//tr')
  188. for tr in proxy_list[1:]:
  189. yield ':'.join(tr.xpath('./td/text()')[0:2])
  190. @staticmethod
  191. def freeProxyEight():
  192. """
  193. 秘密代理IP网站http://www.mimiip.com
  194. """
  195. url_gngao = ['http://www.mimiip.com/gngao/%s' % n for n in range(1, 10)] # 国内高匿
  196. url_gnpu = ['http://www.mimiip.com/gnpu/%s' % n for n in range(1, 10)] # 国内普匿
  197. url_gntou = ['http://www.mimiip.com/gntou/%s' % n for n in range(1, 10)] # 国内透明
  198. url_list = url_gngao + url_gnpu + url_gntou
  199. request = WebRequest()
  200. for url in url_list:
  201. r = request.get(url, use_proxy=True)
  202. proxies = re.findall(r'<td>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})</td>[\w\W].*<td>(\d+)</td>', r.text)
  203. for proxy in proxies:
  204. yield ':'.join(proxy)
  205. @staticmethod
  206. def freeProxyNinth():
  207. """
  208. coderBusy
  209. https://proxy.coderbusy.com/
  210. :return:
  211. """
  212. urls = ['https://proxy.coderbusy.com/classical/country/cn.aspx?page=1']
  213. request = WebRequest()
  214. for url in urls:
  215. r = request.get(url)
  216. proxies = re.findall('data-ip="(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})".+?>(\d+)</td>', r.text)
  217. for proxy in proxies:
  218. yield ':'.join(proxy)
  219. @staticmethod
  220. def freeProxyWallFirst():
  221. """
  222. 墙外网站 cn-proxy
  223. 并没有被墙
  224. :return:
  225. """
  226. urls = ['http://cn-proxy.com/', 'http://cn-proxy.com/archives/218']
  227. request = WebRequest()
  228. for url in urls:
  229. r = request.get(url)
  230. proxies = re.findall(r'<td>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})</td>[\w\W]<td>(\d+)</td>', r.text)
  231. for proxy in proxies:
  232. yield ':'.join(proxy)
  233. @staticmethod
  234. def freeProxyWallSecond():
  235. '''
  236. 并没有被墙
  237. :return:
  238. '''
  239. urls = ['https://proxy-list.org/english/index.php?p=%s' % n for n in range(1, 10)]
  240. request = WebRequest()
  241. import base64
  242. for url in urls:
  243. r = request.get(url)
  244. proxies = re.findall(r"Proxy\('(.*?)'\)", r.text)
  245. for proxy in proxies:
  246. yield base64.b64decode(proxy).decode()
  247. @staticmethod
  248. def freeProxyWallThird():
  249. urls = ['https://list.proxylistplus.com/Fresh-HTTP-Proxy-List-1']
  250. request = WebRequest()
  251. for url in urls:
  252. r = request.get(url)
  253. proxies = re.findall(r'<td>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})</td>[\s\S]*?<td>(\d+)</td>', r.text)
  254. for proxy in proxies:
  255. yield ':'.join(proxy)
  256. import threading
  257. lock = threading.Lock()
  258. success = 0
  259. total = 0
  260. def test_once(proxy):
  261. ip_port = proxy.split(":")
  262. ip = ip_port[0]
  263. port = ip_port[1]
  264. import requests
  265. req_url = "http://www.baidu.com"
  266. proxies = {
  267. "http": "http://%s:%s" % (ip, port),
  268. "https": "https://%s:%s" % (ip, port)
  269. }
  270. global total
  271. try:
  272. response = requests.get(req_url, proxies=proxies, timeout=4)
  273. if response.status_code != 200:
  274. print("unknow error, status code:" + str(response.status_code))
  275. lock.acquire()
  276. total += 1
  277. lock.release()
  278. return 0
  279. print("success")
  280. global success
  281. lock.acquire()
  282. success += 1
  283. total += 1
  284. lock.release()
  285. return 1
  286. except requests.exceptions.Timeout:
  287. print("timeout")
  288. except requests.exceptions.ConnectionError:
  289. print("poxy unusable")
  290. except Exception:
  291. print("request error")
  292. lock.acquire()
  293. total += 1
  294. lock.release()
  295. return 0
  296. def test_batch(iterator):
  297. global success
  298. global total
  299. for proxy in iterator:
  300. t = threading.Thread(target=test_once, args=(proxy,))
  301. t.start()
  302. t.join()
  303. print("success:" + str(success) + "\ttotal:" + str(total))
  304. if __name__ == '__main__':
  305. gg = GetFreeProxy()
  306. # test_batch(gg.freeProxyFirst())
  307. # test_batch(gg.freeProxySecond())
  308. # test_batch(gg.freeProxyFourth())
  309. # test_batch(gg.freeProxyFifth())
  310. # test_batch(gg.freeProxySixth())
  311. # test_batch(gg.freeProxySeventh())
  312. # to do
  313. test_batch(gg.freeProxyEight())
  314. # gg.freeProxyEight()
  315. # test_batch(gg.freeProxyNinth())
  316. # test_batch(gg.freeProxyWallFirst())
  317. # test_batch(gg.freeProxyWallSecond())
  318. # test_batch(gg.freeProxyWallThird())