有没有易懂的 Python 多线程爬虫代码

2024-05-07 21:42

1. 有没有易懂的 Python 多线程爬虫代码

Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL1,我觉得错误的教学指导才是主要问题。常见的经典 Python 多线程、多进程教程多显得偏“重”。而且往往隔靴搔痒,没有深入探讨日常工作中最有用的内容。
传统的例子
简单搜索下“Python 多线程教程”,不难发现几乎所有的教程都给出涉及类和队列的例子:
#Example.py'''
Standard Producer/Consumer Threading Pattern
'''import time 
import threading 
import Queue 

class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue 

def run(self):
while True:
# queue.get() blocks the current thread until
# an item is retrieved.
msg = self._queue.get()
# Checks if the current message is
# the "Poison Pill"
if isinstance(msg, str) and msg == 'quit':                # if so, exists the loop
break
# "Processes" (or in our case, prints) the queue item
print "I'm a thread, and I received %s!!" % msg        # Always be friendly!
print 'Bye byes!'def Producer():
# Queue is used to share items between
# the threads.
queue = Queue.Queue()    # Create an instance of the worker
worker = Consumer(queue)    # start calls the internal run() method to
# kick off the thread
worker.start() 

# variable to keep track of when we started
start_time = time.time()
# While under 5 seconds..
while time.time() - start_time < 5:
# "Produce" a piece of work and stick it in
# the queue for the Consumer to process
queue.put('something at %s' % time.time())        # Sleep a bit just to avoid an absurd number of messages
time.sleep(1)    # This the "poison pill" method of killing a thread.
queue.put('quit')    # wait for the thread to close down
worker.join()if __name__ == '__main__':
Producer()

哈,看起来有些像 Java 不是吗?
我并不是说使用生产者/消费者模型处理多线程/多进程任务是错误的(事实上,这一模型自有其用武之地)。只是,处理日常脚本任务时我们可以使用更有效率的模型。
问题在于…
首先,你需要一个样板类;
其次,你需要一个队列来传递对象;
而且,你还需要在通道两端都构建相应的方法来协助其工作(如果需想要进行双向通信或是保存结果还需要再引入一个队列)。
worker 越多,问题越多
按照这一思路,你现在需要一个 worker 线程的线程池。下面是一篇 IBM 经典教程中的例子——在进行网页检索时通过多线程进行加速。
#Example2.py'''
A more realistic thread pool example 
'''import time 
import threading 
import Queue 
import urllib2 

class Consumer(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self._queue = queue 

def run(self):
while True:
content = self._queue.get()
if isinstance(content, str) and content == 'quit':                break
response = urllib2.urlopen(content)        print 'Bye byes!'def Producer():
urls = [        'http', 'httcom'
'ala.org', 'hle.com'
# etc..
]
queue = Queue.Queue()
worker_threads = build_worker_pool(queue, 4)
start_time = time.time()    # Add the urls to process
for url in urls:
queue.put(url)
# Add the poison pillv
for worker in worker_threads:
queue.put('quit')    for worker in worker_threads:
worker.join()    print 'Done! Time taken: {}'.format(time.time() - start_time)def build_worker_pool(queue, size):
workers = []    for _ in range(size):
worker = Consumer(queue)
worker.start()
workers.append(worker)    return workersif __name__ == '__main__':
Producer()

这段代码能正确的运行,但仔细看看我们需要做些什么:构造不同的方法、追踪一系列的线程,还有为了解决恼人的死锁问题,我们需要进行一系列的 join 操作。这还只是开始……
至此我们回顾了经典的多线程教程,多少有些空洞不是吗?样板化而且易出错,这样事倍功半的风格显然不那么适合日常使用,好在我们还有更好的方法。
何不试试 map
map 这一小巧精致的函数是简捷实现 Python 程序并行化的关键。map 源于 Lisp 这类函数式编程语言。它可以通过一个序列实现两个函数之间的映射。
urls = ['ho.com', 'htdit.com']
results = map(urllib2.urlopen, urls)

上面的这两行代码将 urls 这一序列中的每个元素作为参数传递到 urlopen 方法中,并将所有结果保存到 results 这一列表中。其结果大致相当于:
results = []for url in urls:
results.append(urllib2.urlopen(url))

map 函数一手包办了序列操作、参数传递和结果保存等一系列的操作。
为什么这很重要呢?这是因为借助正确的库,map 可以轻松实现并行化操作。

在 Python 中有个两个库包含了 map 函数: multiprocessing 和它鲜为人知的子库 multiprocessing.dummy.
这里多扯两句: multiprocessing.dummy? mltiprocessing 库的线程版克隆?这是虾米?即便在 multiprocessing 库的官方文档里关于这一子库也只有一句相关描述。而这句描述译成人话基本就是说:"嘛,有这么个东西,你知道就成."相信我,这个库被严重低估了!
dummy 是 multiprocessing 模块的完整克隆,唯一的不同在于 multiprocessing 作用于进程,而 dummy 模块作用于线程(因此也包括了 Python 所有常见的多线程限制)。
所以替换使用这两个库异常容易。你可以针对 IO 密集型任务和 CPU 密集型任务来选择不同的库。2
动手尝试
使用下面的两行代码来引用包含并行化 map 函数的库:
from multiprocessing import Poolfrom multiprocessing.dummy import Pool as ThreadPool

实例化 Pool 对象:
pool = ThreadPool()

这条简单的语句替代了 example2.py 中 build_worker_pool 函数 7 行代码的工作。它生成了一系列的 worker 线程并完成初始化工作、将它们储存在变量中以方便访问。
Pool 对象有一些参数,这里我所需要关注的只是它的第一个参数:processes. 这一参数用于设定线程池中的线程数。其默认值为当前机器 CPU 的核数。
一般来说,执行 CPU 密集型任务时,调用越多的核速度就越快。但是当处理网络密集型任务时,事情有有些难以预计了,通过实验来确定线程池的大小才是明智的。
pool = ThreadPool(4) # Sets the pool size to 4

线程数过多时,切换线程所消耗的时间甚至会超过实际工作时间。对于不同的工作,通过尝试来找到线程池大小的最优值是个不错的主意。
创建好 Pool 对象后,并行化的程序便呼之欲出了。我们来看看改写后的 example2.py
import urllib2 
from multiprocessing.dummy import Pool as ThreadPool 

urls = [    'httorg',
'hon.org/about/',
'hnlamp.com/pub/a/python/2003/04/17/metaclasses.html',


# etc..
]

# Make the Pool of workers
pool = ThreadPool(4) 
# Open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
#close the pool and wait for the work to finish 
pool.close() 
pool.join() 


实际起作用的代码只有 4 行,其中只有一行是关键的。map 函数轻而易举的取代了前文中超过 40 行的例子。为了更有趣一些,我统计了不同方法、不同线程池大小的耗时情况。
# results = [] # for url in urls:#   result = urllib2.urlopen(url)#   results.append(result)# # ------- VERSUS ------- # # # ------- 4 Pool ------- # # pool = ThreadPool(4) # results = pool.map(urllib2.urlopen, urls)# # ------- 8 Pool ------- # # pool = ThreadPool(8) # results = pool.map(urllib2.urlopen, urls)# # ------- 13 Pool ------- # # pool = ThreadPool(13) # results = pool.map(urllib2.urlopen, urls)

结果:
#        Single thread:  14.4 Seconds #               4 Pool:   3.1 Seconds#               8 Pool:   1.4 Seconds#              13 Pool:   1.3 Seconds

很棒的结果不是吗?这一结果也说明了为什么要通过实验来确定线程池的大小。在我的机器上当线程池大小大于 9 带来的收益就十分有限了。

有没有易懂的 Python 多线程爬虫代码

2. python 多线程 爬虫 可以用多少个线程

这个没有固定数值,需要根据你爬取目标的访问速度,还有你服务器的性能配置(内存,cpu)来调整。

如果解决了您的问题请采纳!
如果未解决请继续追问!

3. python爬虫怎么实现多线程

多线程的例子:
import threadingimport timedef show(arg):    time.sleep(1)    print('thread' + str(arg))for i in range(10):    t = threading.Thread(target=show, args=(i,))    t.start()print('main thread stop')
运行效果:

python爬虫怎么实现多线程

4. 请教一道 Python 多线程爬虫的面试题

def saveToFile(FileName,srcList):
    a=0
    srcTuple = (srcList)
    FileName = 'os'+FileName.strip()
    res = mkdir(FileName)
    if res == False:
        return False
    #os.mkdir(FileName)
    os.chdir(FileName)
    que = Queue.Queue()
    for sl in srcList:
        que.put(sl)
    for a in range(0,srcList.__len__()):
        threadD = threadDownload(que,a)
        threadD.start()
        #print threading.enumerate()
    while threading.active_count() != 0:
        if threading.active_count() == 1:
            print FileName+"  is Done"
            return True

5. python爬虫如何利用多线程

多线程的例子:

import threadingimport time  def show(arg):    time.sleep(1)    print('thread' + str(arg))  for i in range(10):    t = threading.Thread(target=show, args=(i,))    t.start() print('main thread stop')

运行效果:


python爬虫如何利用多线程

6. python爬虫创建多少个线程不叫号

一个爬虫的简单框架
一个简单的爬虫框架,主要就是处理网络请求,Scrapy使用的是Twisted(一个事件驱动网络框架,以非阻塞的方式对网络I/O进行异步处理),这里不使用异步处理,等以后再研究这个框架。如果使用的是Python3.4及其以上版本,到可以使用asyncio这个标准库。
这个简单的爬虫使用多线程来处理网络请求,使用线程来处理URL队列中的url,然后将url返回的结果保存在另一个队列中,其它线程在读取这个队列中的数据,然后写到文件中去。
该爬虫主要用下面几个部分组成。
1 URL队列和结果队列
将将要爬去的url放在一个队列中,这里使用标准库Queue。访问url后的结果保存在结果队列中
初始化一个URL队列
from Queue import Queue
urls_queue = Queue()
out_queue = Queue()

2 请求线程
使用多个线程,不停的取URL队列中的url,并进行处理:
import threading

class ThreadCrawl(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:
item = self.queue.get()
self.queue.task_down()

下面是部分标准库Queue的使用方法:
Queue.get([block[, timeout]])
Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available.
Queue.task_done()
Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.
如果队列为空,线程就会被阻塞,直到队列不为空。处理队列中的一条数据后,就需要通知队列已经处理完该条数据。
处理线程
处理结果队列中的数据,并保存到文件中。如果使用多个线程的话,必须要给文件加上锁。
lock = threading.Lock()
f = codecs.open('out.txt', 'w', 'utf8')

当线程需要写入文件的时候,可以这样处理:
with lock:
f.write(something)

程序的执行结果
运行状态:

抓取结果:

源码
代码还不完善,将会持续修改中。
# coding: utf-8
'''
Author mr_zys

Email myzysv5@sina.com 
'''

from Queue import Queue
import threading
import urllib2
import time
import json
import codecs
from bs4 import BeautifulSoup

urls_queue = Queue()
data_queue = Queue()
lock = threading.Lock()
f = codecs.open('out.txt', 'w', 'utf8')


class ThreadUrl(threading.Thread):

def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue

def run(self):
pass


class ThreadCrawl(threading.Thread):

def __init__(self, url, queue, out_queue):
threading.Thread.__init__(self)
self.url = url
self.queue = queue
self.out_queue = out_queue

def run(self):
while True:
item = self.queue.get()
data = self._data_post(item)
try:
req = urllib2.Request(url=self.url, data=data)
res = urllib2.urlopen(req)
except urllib2.HTTPError, e:
raise e.reason
py_data = json.loads(res.read())
res.close()
item['first'] = 'false'
item['pn'] = item['pn'] + 1
success = py_data['success']
if success:
print 'Get success...'
else:
print 'Get fail....'
print 'pn is : %s' % item['pn']
result = py_data['content']['result']
if len(result) != 0:
self.queue.put(item)
print 'now queue size is: %d' % self.queue.qsize()
self.out_queue.put(py_data['content']['result'])
self.queue.task_done()

def _data_post(self, item):
pn = item['pn']
first = 'false'
if pn == 1:
first = 'true'
return 'first=' + first + '&pn=' + str(pn) + '&kd=' + item['kd']

def _item_queue(self):
pass


class ThreadWrite(threading.Thread):

def __init__(self, queue, lock, f):
threading.Thread.__init__(self)
self.queue = queue
self.lock = lock
self.f = f

def run(self):
while True:
item = self.queue.get()
self._parse_data(item)
self.queue.task_done()

def _parse_data(self, item):
for i in item:
l = self._item_to_str(i)
with self.lock:
print 'write %s' % l
self.f.write(l)

def _item_to_str(self, item):
positionName = item['positionName']
positionType = item['positionType']
workYear = item['workYear']
education = item['education']
jobNature = item['jobNature']
companyName = item['companyName']
companyLogo = item['companyLogo']
industryField = item['industryField']
financeStage = item['financeStage']
companyShortName = item['companyShortName']
city = item['city']
salary = item['salary']
positionFirstType = item['positionFirstType']
createTime = item['createTime']
positionId = item['positionId']
return positionName + ' ' + positionType + ' ' + workYear + ' ' + education + ' ' + \
jobNature + ' ' + companyLogo + ' ' + industryField + ' ' + financeStage + ' ' + \
companyShortName + ' ' + city + ' ' + salary + ' ' + positionFirstType + ' ' + \
createTime + ' ' + str(positionId) + '\n'


def main():
for i in range(4):
t = ThreadCrawl(
'', urls_queue, data_queue)
t.setDaemon(True)
t.start()
datas = [
{'first': 'true', 'pn': 1, 'kd': 'Java'}
#{'first': 'true', 'pn': 1, 'kd': 'Python'}
]
for d in datas:
urls_queue.put(d)
for i in range(4):
t = ThreadWrite(data_queue, lock, f)
t.setDaemon(True)
t.start()

urls_queue.join()
data_queue.join()

with lock:
f.close()
print 'data_queue siez: %d' % data_queue.qsize()
main()


总结
主要是熟悉使用Python的多线程编程,以及一些标准库的使用Queue、threading。

7. Python爬虫多线程如何使用多线程

无疑是python,爬虫是python最擅长的方面之一,有许多强大的爬虫库如scrapy。 而node.js虽然也能做爬虫,但在处理多线程方面受到限制,这是硬伤。

Python爬虫多线程如何使用多线程

8. Python 多线程爬虫如何优雅的退出

一般来说,多线程模式下,建议主线程只处理线程本身的调度,不去处理具体业务。通常在创建线程后,join等待所有线程退出。 就题主的问题,可以创建线程一、二之后,主线程等待线程一退出,之后用sys.exit退出。
最新文章
热门文章
推荐阅读