python使用rabbitmq实现网络爬虫示例
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python使用rabbitmq实现网络爬虫示例,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2122字,纯文字阅读大概需要4分钟。
内容图文
![python使用rabbitmq实现网络爬虫示例](/upload/InfoBanner/zyjiaocheng/436/cddff34547db4b4a92a68858a2e27942.jpg)
代码如下:
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.bitsCN.com/")
由于html中某些特殊情况的存在,程序还有待完善。
内容总结
以上是互联网集市为您收集整理的python使用rabbitmq实现网络爬虫示例全部内容,希望文章能够帮你解决python使用rabbitmq实现网络爬虫示例所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。