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爬虫:通过关键字爬取百度图片

使用工具:Python2.7 点我下载 scrapy框架 sublime text3 一。搭建python(Windows版本)  1.安装python2.7 ---然后在cm...

python脚本爬取字体文件的实现方法

前言 大家应该都有所体会,为了提高验证码的识别准确率,我们当然要首先得到足够多的测试数据。验证码下载下来容易,但是需要人脑手工识别着实让人受不了,于是我就想了个折衷的办法——自己造验证码...

Python打印scrapy蜘蛛抓取树结构的方法

本文实例讲述了Python打印scrapy蜘蛛抓取树结构的方法。分享给大家供大家参考。具体如下: 通过下面这段代码可以一目了然的知道scrapy的抓取页面结构,调用也非常简单 #!/...

利用Python3分析sitemap.xml并抓取导出全站链接详解

利用Python3分析sitemap.xml并抓取导出全站链接详解

前言 最近网站从HTTPS转为HTTP,更换了网址,旧网址做了301重定向,折腾有点大,于是在百度站长平台提交网址,不管是主动推送还是手动提交,前提都是要整理网站的链接,手动添加太麻烦,...

Python即时网络爬虫项目启动说明详解

Python即时网络爬虫项目启动说明详解

作为酷爱编程的老程序员,实在按耐不下这个冲动,Python真的是太火了,不断撩拨我的心。 我是对Python存有戒备之心的,想当年我基于Drupal做的系统,使用php语言,当语言升级...