python面向对象多线程爬虫爬取搜狐页面的实例代码


Posted in Python onMay 31, 2018

首先我们需要几个包:requests, lxml, bs4, pymongo, redis

1. 创建爬虫对象,具有的几个行为:抓取页面,解析页面,抽取页面,储存页面

class Spider(object):
 def __init__(self):
  # 状态(是否工作)
  self.status = SpiderStatus.IDLE
 # 抓取页面
 def fetch(self, current_url):
  pass
 # 解析页面
 def parse(self, html_page):
  pass
 # 抽取页面
 def extract(self, html_page):
  pass
 # 储存页面
 def store(self, data_dict):
  pass

2. 设置爬虫属性,没有在爬取和在爬取中,我们用一个类封装, @unique使里面元素独一无二,Enum和unique需要从 enum里面导入:

@unique
class SpiderStatus(Enum):
 IDLE = 0
 WORKING = 1

3. 重写多线程的类:

class SpiderThread(Thread):
 def __init__(self, spider, tasks):
  super().__init__(daemon=True)
  self.spider = spider
  self.tasks = tasks
 def run(self):
  while True:
   pass

4. 现在爬虫的基本结构已经做完了,在main函数创建tasks, Queue需要从queue里面导入:

def main():
 # list没有锁,所以使用Queue比较安全, task_queue=[]也可以使用,Queue 是先进先出结构, 即 FIFO
 task_queue = Queue()
 # 往队列放种子url, 即搜狐手机端的url
 task_queue.put('http://m.sohu,com/')
 # 指定起多少个线程
 spider_threads = [SpiderThread(Spider(), task_queue) for _ in range(10)]
 for spider_thread in spider_threads:
  spider_thread.start()
 # 控制主线程不能停下,如果队列里有东西,任务不能停, 或者spider处于工作状态,也不能停
 while task_queue.empty() or is_any_alive(spider_threads):
  pass
 print('Over')

4-1. 而 is_any_threads则是判断线程里是否有spider还活着,所以我们再写一个函数来封装一下:

def is_any_alive(spider_threads):
 return any([spider_thread.spider.status == SpiderStatus.WORKING
    for spider_thread in spider_threads])

5. 所有的结构已经全部写完,接下来就是可以填补爬虫部分的代码,在SpiderThread(Thread)里面,开始写爬虫运行 run 的方法,即线程起来后,要做的事情:

def run(self):
  while True:
   # 获取url
   current_url = self.tasks_queue.get()
   visited_urls.add(current_url)
   # 把爬虫的status改成working
   self.spider.status = SpiderStatus.WORKING
   # 获取页面
   html_page = self.spider.fetch(current_url)
   # 判断页面是否为空
   if html_page not in [None, '']:
    # 去解析这个页面, 拿到列表
    url_links = self.spider.parse(html_page)
    # 把解析完的结构加到 self.tasks_queue里面来
    # 没有一次性添加到队列的方法 用循环添加算求了
    for url_link in url_links:
     self.tasks_queue.put(url_link)
   # 完成任务,状态变回IDLE
   self.spider.status = SpiderStatus.IDLE

6.  现在可以开始写 Spider()这个类里面的四个方法,首先写fetch()抓取页面里面的:  

@Retry()
 def fetch(self, current_url, *, charsets=('utf-8', ), user_agent=None, proxies=None):
  thread_name = current_thread().name
  print(f'[{thread_name}]: {current_url}')
  headers = {'user-agent': user_agent} if user_agent else {}
  resp = requests.get(current_url,
       headers=headers, proxies=proxies)
  # 判断状态码,只要200的页面
  return decode_page(resp.content, charsets) \
   if resp.status_code == 200 else None

6-1. decode_page是我们在类的外面封装一个解码的函数:

def decode_page(page_bytes, charsets=('utf-8',)):
 page_html = None
 for charset in charsets:
  try:
   page_html = page_bytes.decode(charset)
   break
  except UnicodeDecodeError:
   pass
   # logging.error('Decode:', error)
 return page_html

6-2. @retry是装饰器,用于重试, 因为需要传参,在这里我们用一个类来包装, 所以最后改成@Retry():

# retry的类,重试次数3次,时间5秒(这样写在装饰器就不用传参数类), 异常
class Retry(object):
 def __init__(self, *, retry_times=3, wait_secs=5, errors=(Exception, )):
  self.retry_times = retry_times
  self.wait_secs = wait_secs
  self.errors = errors
 # call 方法传参
 def __call__(self, fn):
  def wrapper(*args, **kwargs):
   for _ in range(self.retry_times):
    try:
     return fn(*args, **kwargs)
    except self.errors as e:
     # 打日志
     logging.error(e)
     # 最小避让 self.wait_secs 再发起请求(最小避让时间)
     sleep((random() + 1) * self.wait_secs)
   return None
  return wrapper()

7. 接下来写解析页面的方法,即 parse():

# 解析页面
 def parse(self, html_page, *, domain='m.sohu.com'):
  soup = BeautifulSoup(html_page, 'lxml')
  url_links = []
  # 找body的有 href 属性的 a 标签
  for a_tag in soup.body.select('a[href]'):
   # 拿到这个属性
   parser = urlparse(a_tag.attrs['href'])
   netloc = parser.netloc or domain
   scheme = parser.scheme or 'http'
   netloc = parser.netloc or 'm.sohu.com'
   # 只爬取 domain 底下的
   if scheme != 'javascript' and netloc == domain:
    path = parser.path
    query = '?' + parser.query if parser.query else ''
    full_url = f'{scheme}://{netloc}{path}{query}'
    if full_url not in visited_urls:
     url_links.append(full_url)
  return url_links

7-1. 我们需要在SpiderThread()的 run方法里面,在

current_url = self.tasks_queue.get()

下面添加

visited_urls.add(current_url)

在类外面再添加一个

visited_urls = set()去重

8. 现在已经能开始抓取到相应的网址。

python面向对象多线程爬虫爬取搜狐页面的实例代码 

总结

以上所述是小编给大家介绍的python面向对象多线程爬虫爬取搜狐页面的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
Python标准库defaultdict模块使用示例
Apr 28 Python
django接入新浪微博OAuth的方法
Jun 29 Python
Python如何快速实现分布式任务
Jul 06 Python
Python实现随机创建电话号码的方法示例
Dec 07 Python
对python调用RPC接口的实例详解
Jan 03 Python
django的ORM模型的实现原理
Mar 04 Python
Python socket聊天脚本代码实例
Jan 02 Python
Matplotlib scatter绘制散点图的方法实现
Jan 02 Python
Python 给下载文件显示进度条和下载时间的实现
Apr 02 Python
解决Jupyter Notebook开始菜单栏Anaconda下消失的问题
Apr 13 Python
scrapy redis配置文件setting参数详解
Nov 18 Python
Flask-SocketIO服务端安装及使用代码示例
Nov 26 Python
Python中if elif else及缩进的使用简述
May 31 #Python
python基于物品协同过滤算法实现代码
May 31 #Python
python写入并获取剪切板内容的实例
May 31 #Python
python3实现基于用户的协同过滤
May 31 #Python
python控制windows剪贴板,向剪贴板中写入图片的实例
May 31 #Python
python用户评论标签匹配的解决方法
May 31 #Python
python批量查询、汉字去重处理CSV文件
May 31 #Python
You might like
ThinkPHP模板比较标签用法详解
2014/06/30 PHP
浅谈COOKIE和SESSION区别
2015/07/19 PHP
PHP编程中尝试程序并发的几种方式总结
2016/03/21 PHP
浅谈Laravel中的一个后期静态绑定
2017/08/11 PHP
Thinkphp5 自定义上传文件名的实现方法
2019/07/23 PHP
Ctrl+Enter提交内容信息
2006/06/26 Javascript
Javascript客户端脚本的设计和应用
2006/08/21 Javascript
javascript工具库代码
2012/03/29 Javascript
js实时获取并显示当前时间的方法
2015/07/31 Javascript
Ubuntu系统下Angularjs开发环境安装
2016/09/01 Javascript
JS框架之vue.js(深入三:组件1)
2016/09/29 Javascript
原生js实现打字动画游戏
2017/02/04 Javascript
使用travis-ci如何持续部署node.js应用详解
2017/07/30 Javascript
详解如何配置vue-cli3.0的vue.config.js
2018/08/23 Javascript
图文讲解用vue-cli脚手架创建vue项目步骤
2019/02/12 Javascript
ES7之Async/await的使用详解
2019/03/28 Javascript
JavaScript 俄罗斯方块游戏实现方法与代码解释
2020/04/08 Javascript
JS如何监听div的resize事件详解
2020/12/03 Javascript
Python面向对象基础入门之编码细节与注意事项
2018/12/11 Python
使用Python3+PyQT5+Pyserial 实现简单的串口工具方法
2019/02/13 Python
使用Python进行体育竞技分析(预测球队成绩)
2019/05/16 Python
通过python实现弹窗广告拦截过程详解
2019/07/10 Python
Python 依赖库太多了该如何管理
2019/11/08 Python
Python3 io文本及原始流I/O工具用法详解
2020/03/23 Python
OpenCV读取与写入图片的实现
2020/10/13 Python
python动态规划算法实例详解
2020/11/22 Python
css3 pointer-events 介绍详解
2017/09/18 HTML / CSS
巴西婴儿用品商店:Bebe Store
2017/11/23 全球购物
马云北大演讲完整版:真心话,什么才是阿里的核心竞争力?
2014/04/04 职场文书
考察现实表现材料
2014/05/19 职场文书
农民工讨薪标语
2014/06/26 职场文书
民警个人对照检查剖析材料
2014/09/17 职场文书
党员思想汇报材料
2014/12/19 职场文书
法制教育主题班会
2015/08/13 职场文书
nginx安装以及配置的详细过程记录
2021/09/15 Servers
一条慢SQL语句引发的改造之路
2022/03/16 MySQL