python使用rabbitmq实现网络爬虫示例
2014-02-20 09:47
961 查看
编写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)
由于html中某些特殊情况的存在,程序还有待完善。
您可能感兴趣的文章:
- Python即时网络爬虫项目启动说明详解" target=_blank>=True
self.queue.task_done()
s=spider()
s.start("//www.jb51.net/")
由于html中某些特殊情况的存在,程序还有待完善。
您可能感兴趣的文章:
- [url=https://www.geek-share.com/detail/2730366330.html]Python即时网络爬虫项目启动说明详解
- [url=https://www.geek-share.com/detail/2694577634.html]Python网络爬虫出现乱码问题的解决方法
- Python网络爬虫实例讲解
- 详解Python网络爬虫功能的基本写法
- 使用Python编写简单网络爬虫抓取视频下载资源
- 以Python的Pyspider为例剖析搜索引擎的网络爬虫实现方法
- python3使用urllib模块制作网络爬虫
- python网络爬虫学习笔记(1)
相关文章推荐
- python使用rabbitmq实现网络爬虫示例
- python3实现网络爬虫(3)--BeautifulSoup使用(2)
- Python案例-网络编程-使用RabbitMQ实现RPC简易分享
- 使用requests+beautifulsoup模块实现python网络爬虫功能
- Python使用wget实现下载网络文件功能示例
- 使用python爬虫实现网络股票信息爬取的demo
- python3实现网络爬虫(6)--正则表达式和BeautifulSoup配合使用
- Python实现可获取网易页面所有文本信息的网易网络爬虫功能示例
- python3实现网络爬虫(7)-- 使用ip代理抓取网页
- python3实现网络爬虫(4)--BeautifulSoup使用(3)
- 简单的网络爬虫的python实现
- 网络资源搜索爬虫(python 3.4.1实现)
- 多线程获取豆瓣网页的网络爬虫(Python实现)
- 使用scrapy实现爬网站例子和实现网络爬虫(蜘蛛)的步骤
- 【使用JSOUP实现网络爬虫】使用DOM方法来遍历一个文档
- 使用Python编写简单网络爬虫抓取视频下载资源
- python 网络爬虫入门-Urllib库的基本使用
- Python实现爬虫爬取NBA数据功能示例
- Python 网络爬虫5 ---- 第一次实现抓取数据并且存放到mysql数据库中
- Python实现爬虫抓取与读写、追加到excel文件操作示例