获取模块
获取模块的逻辑比较简单,从各大网站抓取代理
利用元类的方式获取抓取代理的方法
方便起见,将获取代理的每个方法统一定义为crawl开头,扩展的时候,只需要添加crawl开头的方法即可。
示例如下:
1 # -*- coding: utf-8 -*- 2 from pyquery import PyQuery as pq 3 4 from ProxyPool.utils import get_page 5 6 7 class ProxyMetaclass(type): 8 def __new__(cls, name, bases, attrs): 9 count = 0 10 attrs['__CrawlFunc__'] = [] 11 for k, v in attrs.items(): 12 if 'crawl_' in k: 13 attrs['__CrawlFunc__'] = count 14 count += 1 15 attrs['__CrawlFuncCount__'] = count 16 return type.__new__(cls, name, bases, attrs) 17 18 19 class Crawl(object, metaclass=ProxyMetaclass): 20 def get_proxies(self, callback): 21 proxies = [] 22 for proxy in eval("self.{}()".format(callback)): 23 print("成功获取到代理", proxy) 24 proxies.append(proxy) 25 return proxies 26 27 def crawl_dali66(self, page_count=4): 28 """ 29 获取代理66 30 :param page_count: 页码 31 :return: 代理 32 """ 33 start_url = 'http://www.66ip.cn/{}.html' 34 urls = [start_url.format(page) for page in range(1, page_count+1)] 35 for url in urls: 36 print('Crawling', url) 37 html = get_page(url) 38 if html: 39 doc = pq(html) 40 trs = doc('.containerbox table tr:gt(0)').items() 41 for tr in trs: 42 ip = tr.find('td:nth-child(1)') 43 port = tr.find('td:nth-child(2)') 44 print(':'.join([ip, port])) 45 yield ':'.join([ip, port])
定义成生成器,通过yield返回一个代理。首先获取网页,然后利用pyquery解析,解析出Ip加port的形式的代理然后返回。
然后定义了一个get_proxies方法,将所有以crawl开头的方法调用一遍,获取每个方法返回的代理组合成列表形式返回。
如果要做扩展,只需要添加一个以crawl开头的方法,仿照现有方法将其定义为生成器,抓取其网站的代理,通过yield返回。
浙公网安备 33010602011771号