python使用rabbitmq實現(xiàn)網(wǎng)絡爬蟲示例
更新時間:2014年02月20日 09:47:31 作者:
這篇文章主要介紹了python使用RabbitMQ實現(xiàn)網(wǎng)絡爬蟲的示例,需要的朋友可以參考下
編寫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("http://www.dbjr.com.cn/")
由于html中某些特殊情況的存在,程序還有待完善。
您可能感興趣的文章:
- Python網(wǎng)絡爬蟲神器PyQuery的基本使用教程
- Python爬蟲實例_城市公交網(wǎng)絡站點數(shù)據(jù)的爬取方法
- Python3網(wǎng)絡爬蟲之使用User Agent和代理IP隱藏身份
- Python網(wǎng)絡爬蟲出現(xiàn)亂碼問題的解決方法
- Python網(wǎng)絡爬蟲實例講解
- python3使用urllib模塊制作網(wǎng)絡爬蟲
- 詳解Python網(wǎng)絡爬蟲功能的基本寫法
- 以Python的Pyspider為例剖析搜索引擎的網(wǎng)絡爬蟲實現(xiàn)方法
- 使用Python編寫簡單網(wǎng)絡爬蟲抓取視頻下載資源
- Python發(fā)展史及網(wǎng)絡爬蟲
相關文章
python socket網(wǎng)絡編程之粘包問題詳解
這篇文章主要介紹了python socket網(wǎng)絡編程之粘包問題詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04