getter.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from .utils import get_page
  2. from pyquery import PyQuery as pq
  3. class ProxyMetaclass(type):
  4. """
  5. 爬虫的元类,在FreeProxyGetter类中加入
  6. __CrawlFunc__和__CrawlFuncCount__
  7. 两个参数,分别表示爬虫函数,和爬虫函数的数量。
  8. """
  9. def __new__(cls, name, bases, attrs):
  10. count = 0
  11. attrs['__CrawlFunc__'] = []
  12. for k, v in attrs.items():
  13. if 'crawl_' in k:
  14. attrs['__CrawlFunc__'].append(k)
  15. count += 1
  16. attrs['__CrawlFuncCount__'] = count
  17. return type.__new__(cls, name, bases, attrs)
  18. class FreeProxyGetter(object, metaclass=ProxyMetaclass):
  19. """
  20. 代理爬虫,负责扫描各大代理网站,抓取代理。
  21. 该类有可扩展性,可根据需要自己添加新站点的代理抓取函数,
  22. 但是函数名必须以crawl_开头,返回值必须以"host:port"的形式返回,
  23. 添加器会自动识别并调用此类函数。
  24. """
  25. def get_raw_proxies(self, callback):
  26. proxies = []
  27. print('Callback', callback)
  28. for proxy in eval("self.{}()".format(callback)):
  29. proxies.append(proxy)
  30. return proxies
  31. def crawl_daili66(self, page_count=4):
  32. """
  33. 抓取代理66网的数据。
  34. """
  35. start_url = 'http://www.66ip.cn/{}.html'
  36. urls = [start_url.format(page) for page in range(1, page_count + 1)]
  37. for url in urls:
  38. print('Crawling', url)
  39. html = get_page(url)
  40. if html:
  41. doc = pq(html)
  42. trs = doc('.containerbox table tr:gt(0)').items()
  43. for tr in trs:
  44. ip = tr.find('td:nth-child(1)').text()
  45. port = tr.find('td:nth-child(2)').text()
  46. yield ':'.join([ip, port])
  47. def crawl_proxy360(self):
  48. """
  49. 抓取proxy360网的数据。
  50. """
  51. start_url = 'http://www.proxy360.cn/Region/China'
  52. print('Crawling', start_url)
  53. html = get_page(start_url)
  54. if html:
  55. doc = pq(html)
  56. lines = doc('div[name="list_proxy_ip"]').items()
  57. for line in lines:
  58. ip = line.find('.tbBottomLine:nth-child(1)').text()
  59. port = line.find('.tbBottomLine:nth-child(2)').text()
  60. yield ':'.join([ip, port])
  61. def crawl_goubanjia(self):
  62. start_url = 'http://www.goubanjia.com/free/gngn/index.shtml'
  63. html = get_page(start_url)
  64. if html:
  65. doc = pq(html)
  66. tds = doc('td.ip').items()
  67. for td in tds:
  68. td.find('p').remove()
  69. yield td.text().replace(' ', '')
  70. def crawl_haoip(self):
  71. start_url = 'http://haoip.cc/tiqu.htm'
  72. html = get_page(start_url)
  73. if html:
  74. doc = pq(html)
  75. results = doc('.row .col-xs-12').html().split('<br/>')
  76. for result in results:
  77. if result: yield result.strip()