python使用rabbitmq实现网络爬虫示例


Posted in Python onFebruary 20, 2014

编写tasks.py

from celery import Celery
from tornado.httpclient import HTTPClient
app = Celery('tasks')
app.config_from_object('celeryconfig')
@app.task
def get_html(url):
    http_client = HTTPClient()
    try:
        response = http_client.fetch(url,follow_redirects=True)
        return response.body
    except httpclient.HTTPError as e:
        return None
    http_client.close()

编写celeryconfig.py

CELERY_IMPORTS = ('tasks',)
BROKER_URL = 'amqp://guest@localhost:5672//'
CELERY_RESULT_BACKEND = 'amqp://'

编写spider.py

from tasks import get_html
from queue import Queue
from bs4 import BeautifulSoup
from urllib.parse import urlparse,urljoin
import threading
class spider(object):
    def __init__(self):
        self.visited={}
        self.queue=Queue()
    def process_html(self, html):
        pass
        #print(html)
    def _add_links_to_queue(self,url_base,html):
        soup = BeautifulSoup(html)
        links=soup.find_all('a')
        for link in links:
            try:
                url=link['href']
            except:
                pass
            else:
                url_com=urlparse(url)
                if not url_com.netloc:
                    self.queue.put(urljoin(url_base,url))
                else:
                    self.queue.put(url_com.geturl())
    def start(self,url):
        self.queue.put(url)
        for i in range(20):
            t = threading.Thread(target=self._worker)
            t.daemon = True
            t.start()
        self.queue.join()
    def _worker(self):
        while 1:
            url=self.queue.get()
            if url in self.visited:
                continue
            else:
                result=get_html.delay(url)
                try:
                    html=result.get(timeout=5)
                except Exception as e:
                    print(url)
                    print(e)
                self.process_html(html)
                self._add_links_to_queue(url,html)
                self.visited[url]=True
                self.queue.task_done()
s=spider()
s.start("https://3water.com/")

由于html中某些特殊情况的存在,程序还有待完善。

Python 相关文章推荐
Python的ORM框架SQLObject入门实例
Apr 28 Python
详细分析python3的reduce函数
Dec 05 Python
基于Python的文件类型和字符串详解
Dec 21 Python
python matlibplot绘制3D图形
Jul 02 Python
对python:print打印时加u的含义详解
Dec 15 Python
Pycharm以root权限运行脚本的方法
Jan 19 Python
计算机二级python学习教程(3) python语言基本数据类型
May 16 Python
基于numpy中的expand_dims函数用法
Dec 18 Python
Python基于进程池实现多进程过程解析
Apr 30 Python
keras Lambda自定义层实现数据的切片方式,Lambda传参数
Jun 11 Python
Pycharm添加虚拟解释器报错问题解决方案
Oct 13 Python
python基础之模块的导入
Oct 24 Python
python使用win32com在百度空间插入html元素示例
Feb 20 #Python
python基础教程之类class定义使用方法
Feb 20 #Python
python基础教程之基本内置数据类型介绍
Feb 20 #Python
python实现dict版图遍历示例
Feb 19 #Python
使用python在校内发人人网状态(人人网看状态)
Feb 19 #Python
下载给定网页上图片的方法
Feb 18 #Python
使用python将mdb数据库文件导入postgresql数据库示例
Feb 17 #Python
You might like
解析如何去掉CodeIgniter URL中的index.php
2013/06/25 PHP
php Session存储到Redis的方法
2013/11/04 PHP
php session的应用详细介绍
2017/03/22 PHP
PHP分享图片的生成方法
2018/04/25 PHP
laravel使用数据库测试注意事项
2020/04/10 PHP
js switch case default 的用法示例介绍
2013/10/23 Javascript
JS OffsetParent属性深入解析
2014/01/13 Javascript
ANGULARJS中用NG-BIND指令实现单向绑定的例子
2014/12/08 Javascript
javascript数组去重的六种方法汇总
2015/08/16 Javascript
js实现随机抽选效果、随机抽选红色球效果
2017/01/13 Javascript
jQuery length 和 size()区别总结
2018/04/26 jQuery
详解node Async/Await 更好的异步编程解决方案
2018/05/10 Javascript
详解jQuery设置内容和属性
2019/04/11 jQuery
解决vue单页面多个组件嵌套监听浏览器窗口变化问题
2020/07/30 Javascript
详解vue修改elementUI的分页组件视图没更新问题
2020/11/13 Javascript
pycharm 使用心得(九)解决No Python interpreter selected的问题
2014/06/06 Python
Python实现的数据结构与算法之快速排序详解
2015/04/22 Python
Python基于pygame实现的弹力球效果(附源码)
2015/11/11 Python
Python 制作糗事百科爬虫实例
2016/09/22 Python
详解python里使用正则表达式的全匹配功能
2017/10/19 Python
理解python中生成器用法
2017/12/20 Python
Python 将Matrix、Dict保存到文件的方法
2018/10/30 Python
python-opencv 将连续图片写成视频格式的方法
2019/01/08 Python
完美解决Python matplotlib绘图时汉字显示不正常的问题
2019/01/29 Python
python3利用Socket实现通信的方法示例
2019/05/06 Python
Python3 Tkinter选择路径功能的实现方法
2019/06/14 Python
如何分离django中的媒体、静态文件和网页
2019/11/12 Python
Reebonz中国官网:新加坡奢侈品购物网站
2017/03/17 全球购物
Lulu & Georgia官方网站:购买地毯、家具、抱枕、壁纸、床上用品等
2018/03/19 全球购物
美国时尚大码女装购物网站:Avenue
2019/05/24 全球购物
台湾时尚彩瞳专门店:imeime
2019/08/16 全球购物
个人函授自我鉴定
2014/03/25 职场文书
委托书怎样写
2014/08/30 职场文书
物业保洁员岗位职责
2015/02/13 职场文书
大学生团日活动总结
2015/05/06 职场文书
把77A收信机改造成收音机
2022/04/05 无线电