getter.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. print('Getting', proxy, 'from', callback)
  30. proxies.append(proxy)
  31. return proxies
  32. def crawl_daili66(self, page_count=4):
  33. """
  34. 抓取代理66网的数据。
  35. """
  36. start_url = 'http://www.66ip.cn/{}.html'
  37. urls = [start_url.format(page) for page in range(1, page_count + 1)]
  38. for url in urls:
  39. print('Crawling', url)
  40. html = get_page(url)
  41. if html:
  42. doc = pq(html)
  43. trs = doc('.containerbox table tr:gt(0)').items()
  44. for tr in trs:
  45. ip = tr.find('td:nth-child(1)').text()
  46. port = tr.find('td:nth-child(2)').text()
  47. yield ':'.join([ip, port])
  48. def crawl_proxy360(self):
  49. """
  50. 抓取proxy360网的数据。
  51. """
  52. start_url = 'http://www.proxy360.cn/Region/China'
  53. print('Crawling', start_url)
  54. html = get_page(start_url)
  55. if html:
  56. doc = pq(html)
  57. lines = doc('div[name="list_proxy_ip"]').items()
  58. for line in lines:
  59. ip = line.find('.tbBottomLine:nth-child(1)').text()
  60. port = line.find('.tbBottomLine:nth-child(2)').text()
  61. yield ':'.join([ip, port])
  62. def crawl_goubanjia(self):
  63. start_url = 'http://www.goubanjia.com/free/gngn/index.shtml'
  64. html = get_page(start_url)
  65. if html:
  66. doc = pq(html)
  67. tds = doc('td.ip').items()
  68. for td in tds:
  69. td.find('p').remove()
  70. yield td.text().replace(' ', '')
  71. def crawl_haoip(self):
  72. start_url = 'http://haoip.cc/tiqu.htm'
  73. html = get_page(start_url)
  74. if html:
  75. doc = pq(html)
  76. results = doc('.row .col-xs-12').html().split('<br/>')
  77. for result in results:
  78. if result: yield result.strip()