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中某些特殊情况的存在,程序还有待完善。

相关文章

python3 Scrapy爬虫框架ip代理配置的方法

python3 Scrapy爬虫框架ip代理配置的方法

什么是Scrapy?   Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架,非常出名,非常强悍。所谓的框架就是一个已经被集成了各种功能(高性能异步下载,队列,分布式,...

Python 爬虫图片简单实现

Python 爬虫图片简单实现 经常在逛知乎,有时候希望把一些问题的图片集中保存起来。于是就有了这个程序。这是一个非常简单的图片爬虫程序,只能爬取已经刷出来的部分的图片。由于对这一部分内...

Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】

Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】

本文实例讲述了Python3实现爬虫爬取赶集网列表功能。分享给大家供大家参考,具体如下: python3爬虫之爬取赶集网列表。这几天一直在学习使用python3爬取数据,今天记录一下,代...

python3爬取torrent种子链接实例

python3爬取torrent种子链接实例

本文环境是python3,采用的是urllib,BeautifulSoup搭建。 说下思路,这个项目分为管理器,url管理器,下载器,解析器,html文件生产器。各司其职,在管理器进行调...

Python爬虫爬取美剧网站的实现代码

Python爬虫爬取美剧网站的实现代码

一直有爱看美剧的习惯,一方面锻炼一下英语听力,一方面打发一下时间。之前是能在视频网站上面在线看的,可是自从广电总局的限制令之后,进口的美剧英剧等貌似就不在像以前一样同步更新了。但是,作为...