侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

爬虫代理池Python3WebSpider源代码测试过程解析

Python  /  管理员 发布于 7年前   193

这篇文章主要介绍了爬虫代理池Python3WebSpider源代码测试过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

元类属性的使用

代码

主要关于元类的使用

通过获取由元类生成的爬虫抓取类的部分属性.这里为抓取函数,以相同的字符开头的抓取函数,生成属性列表,这样可以持续调用.目的是可以仅仅添加不同的抓取函数抓取不同的网站,而类的其他部分不用做调整.

部分代码:

class ProxyMetaclass(type):  def __new__(cls, name, bases, attrs):    count = 0    attrs['__CrawlFunc__'] = []    for k, v in attrs.items():      if 'crawl_' in k:        attrs['__CrawlFunc__'].append(k)        count += 1    attrs['__CrawlFuncCount__'] = count    return type.__new__(cls, name, bases, attrs)class Crawler(object, metaclass=ProxyMetaclass):  def get_proxies(self, callback):    proxies = []    for proxy in eval("self.{}()".format(callback)):      print('成功获取到代理', proxy)      proxies.append(proxy)    return proxies      def crawl_daili66(self, page_count=4):    """    获取代理66    :param page_count: 页码    :return: 代理    """    start_url = 'http://www.66ip.cn/{}.html'    urls = [start_url.format(page) for page in range(1, page_count + 1)]    for url in urls:      print('Crawling', url)      html = get_page(url)      if html:        doc = pq(html)        trs = doc('.containerbox table tr:gt(0)').items()        for tr in trs:          ip = tr.find('td:nth-child(1)').text()          port = tr.find('td:nth-child(2)').text()          yield ':'.join([ip, port])

测试方法

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time  : 12/19/19 4:10 PM# @Author : yon# @Email  : @qq.com# @File  : testimport jsonimport refrom pyquery import PyQuery as pqclass ProxyMetaclass(type):  def __new__(cls, name, bases, attrs):    count = 0    attrs['__CrawlFunc__'] = []    for k, v in attrs.items():      print("打印k")      print(k)      print("打印v")      print(v)      if 'crawl_' in k:        attrs['__CrawlFunc__'].append(k)        count += 1    attrs['__CrawlFuncCount__'] = count    return type.__new__(cls, name, bases, attrs)class Crawler(object, metaclass=ProxyMetaclass):  def get_proxies(self, callback):    proxies = []    for proxy in eval("self.{}()".format(callback)):      print('成功获取到代理', proxy)      proxies.append(proxy)    return proxies  def crawl_daili66(self, page_count=4):    """    获取代理66    :param page_count: 页码    :return: 代理    """    start_url = 'http://www.66ip.cn/{}.html'    urls = [start_url.format(page) for page in range(1, page_count + 1)]    for url in urls:      print('Crawling', url)      html = get_page(url)      if html:        doc = pq(html)        trs = doc('.containerbox table tr:gt(0)').items()        for tr in trs:          ip = tr.find('td:nth-child(1)').text()          port = tr.find('td:nth-child(2)').text()          yield ':'.join([ip, port])  def crawl_ip3366(self):    for page in range(1, 4):      start_url = 'http://www.ip3366.net/free/?stype=1&page={}'.format(page)      html = get_page(start_url)      ip_address = re.compile('<tr>\s*<td>(.*?)</td>\s*<td>(.*?)</td>')      # \s * 匹配空格,起到换行作用      re_ip_address = ip_address.findall(html)      for address, port in re_ip_address:        result = address + ':' + port        yield result.replace(' ', '')  def crawl_kuaidaili(self):    for i in range(1, 4):      start_url = 'http://www.kuaidaili.com/free/inha/{}/'.format(i)      html = get_page(start_url)      if html:        ip_address = re.compile('<td data-title="IP">(.*?)</td>')        re_ip_address = ip_address.findall(html)        port = re.compile('<td data-title="PORT">(.*?)</td>')        re_port = port.findall(html)        for address, port in zip(re_ip_address, re_port):          address_port = address + ':' + port          yield address_port.replace(' ', '')  def crawl_xicidaili(self):    for i in range(1, 3):      start_url = 'http://www.xicidaili.com/nn/{}'.format(i)      headers = {        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',        'Cookie': '_free_proxy_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFVEkiJWRjYzc5MmM1MTBiMDMzYTUzNTZjNzA4NjBhNWRjZjliBjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMUp6S2tXT3g5a0FCT01ndzlmWWZqRVJNek1WanRuUDBCbTJUN21GMTBKd3M9BjsARg%3D%3D--2a69429cb2115c6a0cc9a86e0ebe2800c0d471b3',        'Host': 'www.xicidaili.com',        'Referer': 'http://www.xicidaili.com/nn/3',        'Upgrade-Insecure-Requests': '1',      }      html = get_page(start_url, options=headers)      if html:        find_trs = re.compile('<tr class.*?>(.*?)</tr>', re.S)        trs = find_trs.findall(html)        for tr in trs:          find_ip = re.compile('<td>(\d+\.\d+\.\d+\.\d+)</td>')          re_ip_address = find_ip.findall(tr)          find_port = re.compile('<td>(\d+)</td>')          re_port = find_port.findall(tr)          for address, port in zip(re_ip_address, re_port):address_port = address + ':' + portyield address_port.replace(' ', '')  def crawl_ip3366(self):    for i in range(1, 4):      start_url = 'http://www.ip3366.net/?stype=1&page={}'.format(i)      html = get_page(start_url)      if html:        find_tr = re.compile('<tr>(.*?)</tr>', re.S)        trs = find_tr.findall(html)        for s in range(1, len(trs)):          find_ip = re.compile('<td>(\d+\.\d+\.\d+\.\d+)</td>')          re_ip_address = find_ip.findall(trs[s])          find_port = re.compile('<td>(\d+)</td>')          re_port = find_port.findall(trs[s])          for address, port in zip(re_ip_address, re_port):address_port = address + ':' + portyield address_port.replace(' ', '')  def crawl_iphai(self):    start_url = 'http://www.iphai.com/'    html = get_page(start_url)    if html:      find_tr = re.compile('<tr>(.*?)</tr>', re.S)      trs = find_tr.findall(html)      for s in range(1, len(trs)):        find_ip = re.compile('<td>\s+(\d+\.\d+\.\d+\.\d+)\s+</td>', re.S)        re_ip_address = find_ip.findall(trs[s])        find_port = re.compile('<td>\s+(\d+)\s+</td>', re.S)        re_port = find_port.findall(trs[s])        for address, port in zip(re_ip_address, re_port):          address_port = address + ':' + port          yield address_port.replace(' ', '')  def crawl_data5u(self):    start_url = 'http://www.data5u.com/free/gngn/index.shtml'    headers = {      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',      'Accept-Encoding': 'gzip, deflate',      'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',      'Cache-Control': 'max-age=0',      'Connection': 'keep-alive',      'Cookie': 'JSESSIONID=47AA0C887112A2D83EE040405F837A86',      'Host': 'www.data5u.com',      'Referer': 'http://www.data5u.com/free/index.shtml',      'Upgrade-Insecure-Requests': '1',      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',    }    html = get_page(start_url, options=headers)    if html:      ip_address = re.compile('<span><li>(\d+\.\d+\.\d+\.\d+)</li>.*?<li class=\"port.*?>(\d+)</li>', re.S)      re_ip_address = ip_address.findall(html)      for address, port in re_ip_address:        result = address + ':' + port        yield result.replace(' ', '')class Getter():  def __init__(self):    self.crawler = Crawler()  def run(self):    print('获取器开始执行')    for callback_label in range(self.crawler.__CrawlFuncCount__):      print(callback_label)      callback = self.crawler.__CrawlFunc__[callback_label]      print(callback)      # # 获取代理      # proxies = self.crawler.get_proxies(callback)      # sys.stdout.flush()      # for proxy in proxies:      #   self.redis.add(proxy)if __name__ == '__main__':  get = Getter()  get.run()

测试结果

/home/baixiaoxu/PycharmProjects/pytthon-tt/venv/bin/python /home/baixiaoxu/PycharmProjects/pytthon-tt/proxypool/test.py打印k__module__打印v__main__打印k__qualname__打印vCrawler打印kget_proxies打印v<function Crawler.get_proxies at 0x7f905ca5a598>打印kcrawl_daili66打印v<function Crawler.crawl_daili66 at 0x7f905ca5a620>打印kcrawl_ip3366打印v<function Crawler.crawl_ip3366 at 0x7f905ca5a840>打印kcrawl_kuaidaili打印v<function Crawler.crawl_kuaidaili at 0x7f905ca5a730>打印kcrawl_xicidaili打印v<function Crawler.crawl_xicidaili at 0x7f905ca5a7b8>打印kcrawl_iphai打印v<function Crawler.crawl_iphai at 0x7f905ca5a6a8>打印kcrawl_data5u打印v<function Crawler.crawl_data5u at 0x7f905ca5a8c8>打印k__CrawlFunc__打印v['crawl_daili66', 'crawl_ip3366', 'crawl_kuaidaili', 'crawl_xicidaili', 'crawl_iphai', 'crawl_data5u']获取器开始执行0crawl_daili661crawl_ip33662crawl_kuaidaili3crawl_xicidaili4crawl_iphai5crawl_data5u进程完成,退出码 0

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    python序列化与数据持久化实例详解
    下一条:
    python3的UnicodeDecodeError解决方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客