python使用rabbitmq實(shí)現(xiàn)網(wǎng)絡(luò)爬蟲示例
編寫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)絡(luò)爬蟲神器PyQuery的基本使用教程
- Python爬蟲實(shí)例_城市公交網(wǎng)絡(luò)站點(diǎn)數(shù)據(jù)的爬取方法
- Python3網(wǎng)絡(luò)爬蟲之使用User Agent和代理IP隱藏身份
- Python網(wǎng)絡(luò)爬蟲出現(xiàn)亂碼問題的解決方法
- Python網(wǎng)絡(luò)爬蟲實(shí)例講解
- python3使用urllib模塊制作網(wǎng)絡(luò)爬蟲
- 詳解Python網(wǎng)絡(luò)爬蟲功能的基本寫法
- 以Python的Pyspider為例剖析搜索引擎的網(wǎng)絡(luò)爬蟲實(shí)現(xiàn)方法
- 使用Python編寫簡(jiǎn)單網(wǎng)絡(luò)爬蟲抓取視頻下載資源
- Python發(fā)展史及網(wǎng)絡(luò)爬蟲
相關(guān)文章
基于PyQt5制作一個(gè)動(dòng)態(tài)指針時(shí)鐘
這篇文章主要和大家分享如何利用Python中的PyQt5制作一個(gè)動(dòng)態(tài)指針時(shí)鐘來(lái)顯示實(shí)時(shí)時(shí)間,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-02-02
python socket網(wǎng)絡(luò)編程之粘包問題詳解
這篇文章主要介紹了python socket網(wǎng)絡(luò)編程之粘包問題詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧2018-04-04
Pytest使用logging模塊寫日志的實(shí)例詳解
logging是python語(yǔ)言中的一個(gè)日志模塊,專門用來(lái)寫日志的,日志級(jí)別通常分為debug、info、warning、error、critical幾個(gè)級(jí)別,一般情況下,默認(rèn)的日志級(jí)別為warning,在調(diào)試或者測(cè)試階段,下面就快速體驗(yàn)一下logging模塊寫日志的用法,感興趣的朋友跟隨小編一起看看吧2022-12-12
python常用數(shù)據(jù)結(jié)構(gòu)字典梳理
這篇文章主要介紹了python常用數(shù)據(jù)結(jié)構(gòu)字典梳理,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08
Django的用戶模塊與權(quán)限系統(tǒng)的示例代碼
這篇文章主要介紹了Django的用戶模塊與權(quán)限系統(tǒng)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07

