python多线程队列爬虫流程图_python多线程多队列(BeautifulSoup网络爬虫)

程序大概内容如下:

程序中设置两个队列分别为queue负责存放网址,out_queue负责存放网页的源代码。

ThreadUrl线程负责将队列queue中网址的源代码urlopen,存放到out_queue队列中。

DatamineThread线程负责使用BeautifulSoup模块从out_queue网页的源代码中提取出想要的内容并输出。

这只是一个基本的框架,可以根据需求继续扩展。

程序中有很详细的注释,如有有问题跪求指正啊。

import Queue

import threading

import urllib2

import time

from BeautifulSoup import BeautifulSoup

hosts = ["http://yahoo.com","http://taobao.com","http://apple.com",

"http://ibm.com","http://www.amazon.cn"]

queue = Queue.Queue()#存放网址的队列

out_queue = Queue.Queue()#存放网址页面的队列

class ThreadUrl(threading.Thread):

def __init__(self,queue,out_queue):

threading.Thread.__init__(self)

self.queue = queue

self.out_queue = out_queue

def run(self):

while True:

host = self.queue.get()

url = urllib2.urlopen(host)

chunk = url.read()

self.out_queue.put(chunk)#将hosts中的页面传给out_queue

self.queue.task_done()#传入一个相当于完成一个任务

class DatamineThread(threading.Thread):

def __init__(self,out_queue):

threading.Thread.__init__(self)

self.out_queue = out_queue

def run(self):

while True:

chunk = self.out_queue.get()

soup = BeautifulSoup(chunk)#从源代码中搜索title标签的内容

print soup.findAll(['title'])

self.out_queue.task_done()

start = time.time()

def main():

for i in range(5):

t = ThreadUrl(queue,out_queue)#线程任务就是将网址的源代码存放到out_queue队列中

t.setDaemon(True)#设置为守护线程

t.start()

#将网址都存放到queue队列中

for host in hosts:

queue.put(host)

for i in range(5):

dt = DatamineThread(out_queue)#线程任务就是从源代码中解析出

标签内的内容

dt.setDaemon(True)

dt.start()

queue.join()#线程依次执行,主线程最后执行

out_queue.join()

main()

print "Total time :%s"%(time.time()-start)

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com

特别注意:本站所有转载文章言论不代表本站观点!

本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
爬虫中,多线程队列是非常常见的技术应用。下面是它们在爬虫中的应用示例: 1. 多线程:使用多线可以提高爬取数据的效率,同时可以并发处理多个请求。例如,可以将爬虫程序分为多个线程,每个线程负责处理一个请求,这样可以同时发送多个请求并同时处理响应。 2. 队列:使用队列可以实现任务的调度和管理。例如,可以将待爬取的URL放入队列中,然后创建多个爬虫线程从队列中获取URL,并进行相应的爬取操作。这样可以有效地控制任务的执行顺序,避免资源竞争和重复爬取。 综合应用示例: ```python import threading import queue import requests # 创建队列 url_queue = queue.Queue() # 定义爬虫函数 def crawler(): while not url_queue.empty(): url = url_queue.get() # 发送请求并处理响应 response = requests.get(url) # 其他处理操作... # 添加待爬取的URL到队列 url_queue.put('http://example.com/page1') url_queue.put('http://example.com/page2') url_queue.put('http://example.com/page3') # 创建多个爬虫线程 num_threads = 3 threads = [] for _ in range(num_threads): t = threading.Thread(target=crawler) threads.append(t) # 启动线程 for t in threads: t.start() # 等待所有线程执行完毕 for t in threads: t.join() # 所有任务完成 print("All tasks finished.") ``` 这个示例展示了如何使用多线程队列来进行爬虫任务的并发处理和调度。通过将待爬取的URL放入队列中,然后创建多个爬虫线程从队列中获取URL并进行相应的爬取操作,可以实现高效的爬取任务处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值