python使用rabbitmq实现网络爬虫示例
更新时间:2014年02月20日 09:47:31 作者:
这篇文章主要介绍了python使用RabbitMQ实现网络爬虫的示例,需要的朋友可以参考下
编写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("https://www.jb51.net/")
由于html中某些特殊情况的存在,程序还有待完善。
相关文章
Python实现读取HTML表格 pd.read_html()
这篇文章主要介绍了Python实现读取HTML表格 pd.read_html(),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-07-07
Python的collections模块中的OrderedDict有序字典
字典是无序的,但是collections的OrderedDict类为我们提供了一个有序的字典结构,名副其实的Ordered+Dict,下面通过两个例子来简单了解下Python的collections模块中的OrderedDict有序字典:2016-07-07
Python+tkinter使用80行代码实现一个计算器实例
这篇文章主要介绍了Python+tkinter使用80行代码实现一个计算器实例,具有一定借鉴价值,需要的朋友可以参考下2018-01-01
Python3+Django get/post请求实现教程详解
这篇文章主要介绍了Python3+Django get/post请求实现教程详解,需要的朋友可以参考下2021-02-02


最新评论