1.多线程
单线程爬虫的问题
- 因为爬虫多为IO密集型的程序,而IO处理速度并不是很快,因此速度不会太快
- 如果IO卡顿,直接影响速度
爬虫使用多线程来处理网络请求,使用线程来处理URL队列中的url,然后将url返回的结果保存在另一个队列中,其它线程在读取这个队列中的数据,然后写到文件中
Queue模块中的常用方法
Python的Queue模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列PriorityQueue。这些队列都实现了锁原语,能够在多线程中直接使用。可以使用队列来实现线程间的同步
- Queue.qsize() 返回队列的大小
- Queue.empty() 如果队列为空,返回True,反之False
- Queue.full() 如果队列满了,返回True,反之False
- Queue.full 与 maxsize 大小对应
- Queue.get([block[, timeout]])获取队列,timeout等待时间
- Queue.get_nowait() 相当Queue.get(False)
- Queue.put(item) 写入队列,timeout等待时间
- Queue.put_nowait(item) 相当Queue.put(item, False)
- Queue.task_done() 在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
- Queue.join() 实际上意味着等到队列为空,再执行别的操作
1.1线程
import requests
from fake_useragent import UserAgent
from time import sleep
from queue import Queue
from threading import Thread
class MyThread(Thread):
def __init__(self, url_queue):
super().__init__()
self.url_queue = url_queue
def run(self):
while not self.url_queue.empty():
url = self.url_queue.get()
# print(url)
# 获取数据
headers = {'User-Agent': UserAgent().chrome}
response = requests.get(url, headers=headers)
if response.status_code == 200:
print(f'获取成功:{url}')
sleep(3)
if __name__ == "__main__":
url_queue = Queue()
#初始化需要爬虫的url
for i in range(1,11):
url = f'https://www.maoyan.com/films?showType=3&requestCode=cb2bc26325e33ea36bdb495bd842a4697o5ed&offset={30*i}'
url_queue.put(url)
threads = []
for j in range(3):
# 创建线程
t = MyThread(url_queue)
threads.append(t)
# 启动线程
t.start()
for t in threads:
t.join()
1.2类线程:就是在自定义的 MyThread 类中的 spider 方法中,你没有使用 self 参数来引用该实例的 url_queue 属性。因此,修改 run 方法的定义,将 self 参数添加到方法的参数列表中,并使用 self.url_queue 来引用队列。
import requests
from fake_useragent import UserAgent
from time import sleep
from queue import Queue
from threading import Thread
class MyThread(Thread):
def __init__(self, url_queue):
super().__init__()
self.url_queue = url_queue
def run(self):
while not self.url_queue.empty():
url = self.url_queue.get()
# print(url)
# 获取数据
headers = {'User-Agent': UserAgent().chrome}
response = requests.get(url, headers=headers)
if response.status_code == 200:
print(f'获取成功:{url}')
sleep(3)
if __name__ == "__main__":
url_queue = Queue()
#初始化需要爬虫的url
for i in range(1,11):
url = f'https://www.maoyan.com/films?showType=3&requestCode=cb2bc26325e33ea36bdb495bd842a4697o5ed&offset={30*i}'
url_queue.put(url)
threads = []
for j in range(3):
# 创建线程
t = MyThread(url_queue)
threads.append(t)
# 启动线程
t.start()
for t in threads:
t.join()
2.多进程
multiprocessing是python的多进程管理包,和threading.Thread类似
multiprocessing模块
multiprocessing模块可以让程序员在给定的机器上充分的利用CPU。在multiprocessing中,通过创建Process对象生成进程,然后调用它的start()方法
Manager类,实现数据共享
在使用并发设计的时候最好尽可能的避免共享数据,尤其是在使用多进程的时候。 如果你真有需要 要共享数据,可以使用由Manager()返回的manager提供list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Barrier, Queue, Value and Array类型的支持
from multiprocessing import Process,Manager,Lock
def print_num(info_queue,l,lo):
with lo:
for n in l:
info_queue.put(n)
def updata_num(info_queue,lo):
with lo:
while not info_queue.empty():
print(info_queue.get())
if __name__ == '__main__':
manager = Manager()
into_html = manager.Queue()
lock = Lock()
a = [1, 2, 3, 4, 5]
b = [11, 12, 13, 14, 15]
p1 = Process(target=print_num,args=(into_html,a,lock))
p1.start()
p2 = Process(target=print_num,args=(into_html,b,lock))
p2.start()
p3 = Process(target=updata_num,args=(into_html,lock))
p3.start()
p1.join()
p2.join()
p3.join()
from multiprocessing import Process
from multiprocessing import Manager
import time
from fake_useragent import UserAgent
import requests
from time import sleep
def spider(url_queue):
while not url_queue.empty():
try:
url = url_queue.get(timeout = 1)
# headers = {'User-Agent':UserAgent().chrome}
print(url)
# resp = requests.get(url,headers = headers)
# 处理响应结果
# for d in resp.json().get('data'):
# print(f'tid:{d.get("tid")} topic:{d.get("topicName")} content:{d.get("content")}')
sleep(1)
# if resp.status_code == 200:
# print(f'成功获取第{i}页数据')
except Exception as e:
print(e)
if __name__ == '__main__':
url_queue = Manager().Queue()
for i in range(1,11):
url = f'https://www.hupu.com/home/v1/news?pageNo={i}&pageSize=50'
url_queue.put(url)
all_process = []
for i in range(3):
p1 = Process(target=spider,args=(url_queue,))
p1.start()
all_process.append(p1)
[p.join() for p in all_process]
3.进程池
-
进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。
-
进程池中有两个方法:
- apply同步执行-串行
- apply_async异步执行-并行
from multiprocessing import Pool,Manager
def print_num(info_queue,l):
for n in l:
info_queue.put(n)
def updata_num(info_queue):
while not info_queue.empty():
print(info_queue.get())
if __name__ == '__main__':
html_queue =Manager().Queue()
a=[11,12,13,14,15]
b=[1,2,3,4,5]
pool = Pool(3)
pool.apply_async(func=print_num,args=(html_queue,a))
pool.apply_async(func=print_num,args=(html_queue,b))
pool.apply_async(func=updata_num,args=(html_queue,))
pool.close() #这里join一定是在close之后,且必须要加join,否则主进程不等待创建的子进程执行完毕
pool.join() # 进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭
from multiprocessing import Pool,Manager
from time import sleep
def spider(url_queue):
while not url_queue.empty():
try:
url = url_queue.get(timeout = 1)
print(url)
sleep(1)
except Exception as e:
print(e)
if __name__ == '__main__':
url_queue = Manager().Queue()
for i in range(1,11):
url = f'https://www.hupu.com/home/v1/news?pageNo={i}&pageSize=50'
url_queue.put(url)
pool = Pool(3)
pool.apply_async(func=spider,args=(url_queue,))
pool.apply_async(func=spider,args=(url_queue,))
pool.apply_async(func=spider,args=(url_queue,))
pool.close()
pool.join()
4.协程
网络爬虫速度效率慢,多部分在于阻塞IO这块(网络/磁盘)。在阻塞时,CPU的中内核是可以处理别的非IO操作。因此可以考虑使用协程来提升爬虫效率,这种操作的技术就是协程。
协程一种轻量级线程,拥有自己的寄存器上下文和栈,本质是一个进程
相对于多进程,无需线程上下文切换的开销,无需原子操作锁定及同步的开销
简单的说就是让阻塞的子程序让出CPU给可以执行的子程序
一个进程包含多个线程,一个线程可以包含多个协程
多个线程相对独立,线程的切换受系统控制。 多个协程也相对独立,但是其切换由程序自己控制。
4.1安装
pip install aiohttp
import aiohttp
import asyncio
async def first():
async with aiohttp.ClientSession() as session: # aiohttp.ClientSession() == import requests 模块
async with session.get('http://httpbin.org/get') as resp:
rs = await resp.text()
print(rs)
headers = {'User-Agent':'aaaaaa123'}
async def test_header():
async with aiohttp.ClientSession(headers= headers) as session: # aiohttp.ClientSession() == import requests 模块
async with session.get('http://httpbin.org/get') as resp:
rs = await resp.text()
print(rs)
async def test_params():
async with aiohttp.ClientSession(headers= headers) as session: # aiohttp.ClientSession() == import requests 模块
async with session.get('http://httpbin.org/get',params={'name':'bjsxt'}) as resp:
rs = await resp.text()
print(rs)
async def test_cookie():
async with aiohttp.ClientSession(headers= headers,cookies={'token':'sxt123id'}) as session: # aiohttp.ClientSession() == import requests 模块
async with session.get('http://httpbin.org/get',params={'name':'bjsxt'}) as resp:
rs = await resp.text()
print(rs)
async def test_proxy():
async with aiohttp.ClientSession(headers= headers,cookies={'token':'sxt123id'}) as session: # aiohttp.ClientSession() == import requests 模块
async with session.get('http://httpbin.org/get',params={'name':'bjsxt'},proxy = 'http://name:pwd@ip:port' ) as resp:
rs = await resp.text()
print(rs)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(test_cookie())