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("//www.haodaima.com/")

由于html中某些特殊情况的存在,程序还有待完善。

以上就是python使用rabbitmq实现网络爬虫示例。加倍努力,证明你想要的不是空中楼阁。胜利是在多次失败之后才姗姗而来。更多关于python使用rabbitmq实现网络爬虫示例请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战