getFreeProxy.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. import os
  18. try:
  19. from configparser import ConfigParser # py3
  20. except:
  21. from ConfigParser import ConfigParser # py2
  22. try:
  23. from importlib import reload # py3 实际不会实用,只是为了不显示语法错误
  24. except:
  25. reload(sys)
  26. sys.setdefaultencoding('utf-8')
  27. sys.path.append('..')
  28. from Util.utilFunction import robustCrawl, getHtmlTree
  29. from Util.WebRequest import WebRequest
  30. from Util.utilFunction import verifyProxyFormat
  31. # for debug to disable insecureWarning
  32. requests.packages.urllib3.disable_warnings()
  33. """
  34. 66ip.cn
  35. data5u.com
  36. xicidaili.com
  37. goubanjia.com
  38. xdaili.cn
  39. kuaidaili.com
  40. cn-proxy.com
  41. proxy-list.org
  42. www.mimiip.com to do
  43. """
  44. class GetFreeProxy(object):
  45. """
  46. proxy getter
  47. """
  48. pwd = os.path.split(os.path.realpath(__file__))[0]
  49. config_path = os.path.join(os.path.split(pwd)[0], 'Config.ini')
  50. config_file = ConfigParser()
  51. config_file.read(config_path)
  52. if config_file.has_option('WallProxy', 'proxy'):
  53. WallProxy = config_file.get('WallProxy', 'proxy')
  54. wall_proxies = {"http": "http://{}".format(WallProxy), "https": "https://{}".format(WallProxy)}
  55. else:
  56. wall_proxies = None
  57. def __init__(self):
  58. pass
  59. @staticmethod
  60. def freeProxyFirst(page=10):
  61. """
  62. 无忧代理 http://www.data5u.com/
  63. 几乎没有能用的
  64. :param page: 页数
  65. :return:
  66. """
  67. url_list = [
  68. 'http://www.data5u.com/',
  69. 'http://www.data5u.com/free/gngn/index.shtml',
  70. 'http://www.data5u.com/free/gnpt/index.shtml'
  71. ]
  72. for url in url_list:
  73. html_tree = getHtmlTree(url)
  74. ul_list = html_tree.xpath('//ul[@class="l2"]')
  75. for ul in ul_list:
  76. try:
  77. yield ':'.join(ul.xpath('.//li/text()')[0:2])
  78. except Exception as e:
  79. print(e)
  80. @staticmethod
  81. def freeProxySecond(area=33, page=1):
  82. """
  83. 代理66 http://www.66ip.cn/
  84. :param area: 抓取代理页数,page=1北京代理页,page=2上海代理页......
  85. :param page: 翻页
  86. :return:
  87. """
  88. area = 33 if area > 33 else area
  89. for area_index in range(1, area + 1):
  90. for i in range(1, page + 1):
  91. url = "http://www.66ip.cn/areaindex_{}/{}.html".format(area_index, i)
  92. html_tree = getHtmlTree(url)
  93. tr_list = html_tree.xpath("//*[@id='footer']/div/table/tr[position()>1]")
  94. if len(tr_list) == 0:
  95. continue
  96. for tr in tr_list:
  97. yield tr.xpath("./td[1]/text()")[0] + ":" + tr.xpath("./td[2]/text()")[0]
  98. break
  99. @staticmethod
  100. def freeProxyThird(days=1):
  101. """
  102. ip181 http://www.ip181.com/ 不能用了
  103. :param days:
  104. :return:
  105. """
  106. url = 'http://www.ip181.com/'
  107. html_tree = getHtmlTree(url)
  108. try:
  109. tr_list = html_tree.xpath('//tr')[1:]
  110. for tr in tr_list:
  111. yield ':'.join(tr.xpath('./td/text()')[0:2])
  112. except Exception as e:
  113. pass
  114. @staticmethod
  115. def freeProxyFourth(page_count=2):
  116. """
  117. 西刺代理 http://www.xicidaili.com
  118. :return:
  119. """
  120. url_list = [
  121. 'http://www.xicidaili.com/nn/', # 高匿
  122. 'http://www.xicidaili.com/nt/', # 透明
  123. ]
  124. for each_url in url_list:
  125. for i in range(1, page_count + 1):
  126. page_url = each_url + str(i)
  127. tree = getHtmlTree(page_url)
  128. proxy_list = tree.xpath('.//table[@id="ip_list"]//tr[position()>1]')
  129. for proxy in proxy_list:
  130. try:
  131. yield ':'.join(proxy.xpath('./td/text()')[0:2])
  132. except Exception as e:
  133. pass
  134. @staticmethod
  135. def freeProxyFifth():
  136. """
  137. guobanjia http://www.goubanjia.com/
  138. :return:
  139. """
  140. url = "http://www.goubanjia.com/"
  141. tree = getHtmlTree(url)
  142. proxy_list = tree.xpath('//td[@class="ip"]')
  143. # 此网站有隐藏的数字干扰,或抓取到多余的数字或.符号
  144. # 需要过滤掉<p style="display:none;">的内容
  145. xpath_str = """.//*[not(contains(@style, 'display: none'))
  146. and not(contains(@style, 'display:none'))
  147. and not(contains(@class, 'port'))
  148. ]/text()
  149. """
  150. for each_proxy in proxy_list:
  151. try:
  152. # :符号裸放在td下,其他放在div span p中,先分割找出ip,再找port
  153. ip_addr = ''.join(each_proxy.xpath(xpath_str))
  154. port = each_proxy.xpath(".//span[contains(@class, 'port')]/text()")[0]
  155. yield '{}:{}'.format(ip_addr, port)
  156. except Exception as e:
  157. pass
  158. @staticmethod
  159. def freeProxySixth():
  160. """
  161. 讯代理 http://www.xdaili.cn/
  162. :return:
  163. """
  164. url = 'http://www.xdaili.cn/ipagent/freeip/getFreeIps?page=1&rows=10'
  165. request = WebRequest()
  166. try:
  167. res = request.get(url).json()
  168. for row in res['RESULT']['rows']:
  169. yield '{}:{}'.format(row['ip'], row['port'])
  170. except Exception as e:
  171. pass
  172. @staticmethod
  173. def freeProxySeventh():
  174. """
  175. 快代理 https://www.kuaidaili.com
  176. """
  177. url_list = [
  178. 'https://www.kuaidaili.com/free/inha/{page}/',
  179. 'https://www.kuaidaili.com/free/intr/{page}/'
  180. ]
  181. for url in url_list:
  182. for page in range(1, 5):
  183. page_url = url.format(page=page)
  184. tree = getHtmlTree(page_url)
  185. proxy_list = tree.xpath('.//table//tr')
  186. for tr in proxy_list[1:]:
  187. yield ':'.join(tr.xpath('./td/text()')[0:2])
  188. @staticmethod
  189. def freeProxyEight():
  190. """
  191. 秘密代理 http://www.mimiip.com
  192. """
  193. url_gngao = ['http://www.mimiip.com/gngao/%s' % n for n in range(1, 10)] # 国内高匿
  194. url_gnpu = ['http://www.mimiip.com/gnpu/%s' % n for n in range(1, 10)] # 国内普匿
  195. url_gntou = ['http://www.mimiip.com/gntou/%s' % n for n in range(1, 10)] # 国内透明
  196. url_list = url_gngao + url_gnpu + url_gntou
  197. request = WebRequest()
  198. for url in url_list:
  199. r = request.get(url, use_proxy=True)
  200. 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)
  201. for proxy in proxies:
  202. yield ':'.join(proxy)
  203. @staticmethod
  204. def freeProxyNinth():
  205. """
  206. 码农代理 https://proxy.coderbusy.com/
  207. :return:
  208. """
  209. urls = ['https://proxy.coderbusy.com/classical/country/cn.aspx?page=1']
  210. request = WebRequest()
  211. for url in urls:
  212. r = request.get(url)
  213. proxies = re.findall('data-ip="(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})".+?>(\d+)</td>', r.text)
  214. for proxy in proxies:
  215. yield ':'.join(proxy)
  216. @staticmethod
  217. def freeProxyTen():
  218. """
  219. 云代理 http://www.ip3366.net/free/
  220. :return:
  221. """
  222. urls = ['http://www.ip3366.net/free/']
  223. request = WebRequest()
  224. for url in urls:
  225. r = request.get(url)
  226. 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)
  227. for proxy in proxies:
  228. yield ":".join(proxy)
  229. @staticmethod
  230. def freeProxyEleven():
  231. """
  232. IP海 http://www.iphai.com/free/ng
  233. :return:
  234. """
  235. urls = [
  236. 'http://www.iphai.com/free/ng',
  237. 'http://www.iphai.com/free/np',
  238. 'http://www.iphai.com/free/wg',
  239. 'http://www.iphai.com/free/wp'
  240. ]
  241. request = WebRequest()
  242. for url in urls:
  243. r = request.get(url)
  244. proxies = re.findall(r'<td>\s*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*?</td>[\s\S]*?<td>\s*?(\d+)\s*?</td>',
  245. r.text)
  246. for proxy in proxies:
  247. yield ":".join(proxy)
  248. @staticmethod
  249. def freeProxyTwelve(page_count=8):
  250. """
  251. guobanjia http://ip.jiangxianli.com/?page=
  252. 免费代理库
  253. 超多量
  254. :return:
  255. """
  256. for i in range(1, page_count + 1):
  257. url = 'http://ip.jiangxianli.com/?page={}'.format(i)
  258. # print(url)
  259. html_tree = getHtmlTree(url)
  260. tr_list = html_tree.xpath("/html/body/div[1]/div/div[1]/div[2]/table/tbody/tr")
  261. if len(tr_list) == 0:
  262. continue
  263. for tr in tr_list:
  264. yield tr.xpath("./td[2]/text()")[0] + ":" + tr.xpath("./td[3]/text()")[0]
  265. @staticmethod
  266. def freeProxyWallFirst():
  267. """
  268. 墙外网站 cn-proxy
  269. :return:
  270. """
  271. kwargs = {}
  272. if GetFreeProxy.wall_proxies:
  273. kwargs['proxies'] = GetFreeProxy.wall_proxies
  274. else:
  275. return
  276. urls = ['http://cn-proxy.com/', 'http://cn-proxy.com/archives/218']
  277. request = WebRequest()
  278. for url in urls:
  279. kwargs['url'] = url
  280. r = request.get(**kwargs)
  281. 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)
  282. for proxy in proxies:
  283. yield ':'.join(proxy)
  284. @staticmethod
  285. def freeProxyWallSecond():
  286. """
  287. https://proxy-list.org/english/index.php
  288. :return:
  289. """
  290. kwargs = {}
  291. if GetFreeProxy.wall_proxies:
  292. kwargs['proxies'] = GetFreeProxy.wall_proxies
  293. else:
  294. return
  295. urls = ['https://proxy-list.org/english/index.php?p=%s' % n for n in range(1, 10)]
  296. request = WebRequest()
  297. import base64
  298. for url in urls:
  299. kwargs['url'] = url
  300. r = request.get(**kwargs)
  301. proxies = re.findall(r"Proxy\('(.*?)'\)", r.text)
  302. for proxy in proxies:
  303. yield base64.b64decode(proxy).decode()
  304. @staticmethod
  305. def freeProxyWallThird():
  306. kwargs = {}
  307. if GetFreeProxy.wall_proxies:
  308. kwargs['proxies'] = GetFreeProxy.wall_proxies
  309. else:
  310. return
  311. urls = ['https://list.proxylistplus.com/Fresh-HTTP-Proxy-List-1']
  312. request = WebRequest()
  313. for url in urls:
  314. kwargs['url'] = url
  315. r = request.get(**kwargs)
  316. 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)
  317. for proxy in proxies:
  318. yield ':'.join(proxy)
  319. if __name__ == '__main__':
  320. gg = GetFreeProxy()
  321. # test_batch(gg.freeProxyFirst())
  322. # test_batch(gg.freeProxySecond())
  323. # test_batch(gg.freeProxyFourth())
  324. # test_batch(gg.freeProxyFifth())
  325. # test_batch(gg.freeProxySixth())
  326. # test_batch(gg.freeProxySeventh())
  327. # test_batch(gg.freeProxyEight())
  328. # test_batch(gg.freeProxyNinth())
  329. # test_batch(gg.freeProxyTen())
  330. # test_batch(gg.freeProxyEleven())
  331. proxy_iter = gg.freeProxyTwelve()
  332. proxy_set = set()
  333. for proxy in proxy_iter:
  334. proxy = proxy.strip()
  335. if proxy and verifyProxyFormat(proxy):
  336. #self.log.info('{func}: fetch proxy {proxy}'.format(func=proxyGetter, proxy=proxy))
  337. proxy_set.add(proxy)
  338. #else:
  339. #self.log.error('{func}: fetch proxy {proxy} error'.format(func=proxyGetter, proxy=proxy))
  340. # store
  341. for proxy in proxy_set:
  342. print(proxy)
  343. # test_batch(gg.freeProxyTwelve())
  344. # test_batch(gg.freeProxyWallFirst())
  345. # test_batch(gg.freeProxyWallSecond())
  346. # test_batch(gg.freeProxyWallThird())
  347. for e in gg.freeProxyWallThird():
  348. print(e)