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

yipeiwu_com5年前Python爬虫

编写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("//www.jb51.net/")

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

相关文章

Python学习笔记之抓取某只基金历史净值数据实战案例

Python学习笔记之抓取某只基金历史净值数据实战案例

本文实例讲述了Python抓取某只基金历史净值数据。分享给大家供大家参考,具体如下: http://fund.eastmoney.com/f10/jjjz_519961.html 1、...

python编写爬虫小程序

起因 深夜忽然想下载一点电子书来扩充一下kindle,就想起来python学得太浅,什么“装饰器”啊、“多线程”啊都没有学到。 想到廖雪峰大神的python教程很经典、很著名。就想找找有...

Python使用mongodb保存爬取豆瓣电影的数据过程解析

创建爬虫项目douban scrapy startproject douban 设置items.py文件,存储要保存的数据类型和字段名称 # -*- coding: utf-8...

Python爬虫之模拟知乎登录的方法教程

Python爬虫之模拟知乎登录的方法教程

前言 对于经常写爬虫的大家都知道,有些页面在登录之前是被禁止抓取的,比如知乎的话题页面就要求用户登录才能访问,而 “登录” 离不开 HTTP 中的 Cookie 技术。 登录原理 Coo...

Phantomjs抓取渲染JS后的网页(Python代码)

最近需要爬取某网站,无奈页面都是JS渲染后生成的,普通的爬虫框架搞不定,于是想到用Phantomjs搭一个代理。 Python调用Phantomjs貌似没有现成的第三方库(如果有,请告知...