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爬虫爬取幽默笑话网站

爬取网站为:http://xiaohua.zol.com.cn/youmo/ 查看网页机构,爬取笑话内容时存在如下问题: 1、每页需要进入“查看更多”链接下面网页进行进一步爬取内容每页查...

使用Python程序抓取新浪在国内的所有IP的教程

数据分析,特别是网站分析中需要对访问者的IP进行分析,分析IP中主要是区分来访者的省份+城市+行政区数据,考虑到目前纯真IP数据库并没有把这些数据做很好的区分,于是寻找了另外一个可行的方...

Python使用scrapy抓取网站sitemap信息的方法

本文实例讲述了Python使用scrapy抓取网站sitemap信息的方法。分享给大家供大家参考。具体如下: import re from scrapy.spider import...

Python爬虫实现爬取百度百科词条功能实例

Python爬虫实现爬取百度百科词条功能实例

本文实例讲述了Python爬虫实现爬取百度百科词条功能。分享给大家供大家参考,具体如下: 爬虫是一个自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成。爬虫从一个或...

python3爬取数据至mysql的方法

本文实例为大家分享了python3爬取数据至mysql的具体代码,供大家参考,具体内容如下 直接贴代码 #!/usr/local/bin/python3.5 # -*- codin...