网络爬虫之第四章爬虫进阶之多线程爬虫

多线程爬虫

有些时候,好比下载图片,由于下载图片是一个耗时的操做。若是采用以前那种同步的方式下载。那效率肯会特别慢。这时候咱们就能够考虑使用多线程的方式来下载图片。html

多线程介绍:

多线程是为了同步完成多项任务,经过提升资源使用效率来提升系统的效率。线程是在同一时间须要完成多项任务的时候实现的。
最简单的比喻多线程就像火车的每一节车箱,而进程则是火车。车箱离开火车是没法跑动的,同理火车也能够有多节车箱。多线程的出现就是为了提升效率。同时它的出现也带来了一些问题。更多介绍请参考:https://baike.baidu.com/item/多线程/1190404?fr=aladdinpython

threading模块介绍:

threading模块是python中专门提供用来作多线程编程的模块。threading模块中最经常使用的类是Thread。如下看一个简单的多线程程序:编程

import threading
import time

def coding():
    for x in range(3):
        print('%s正在写代码' % x)
        time.sleep(1)

def drawing():
    for x in range(3):
        print('%s正在画图' % x)
        time.sleep(1)


def single_thread():
    coding()
    drawing()

def multi_thread():
    t1 = threading.Thread(target=coding)
    t2 = threading.Thread(target=drawing)

    t1.start()
    t2.start()

if __name__ == '__main__':
    multi_thread()

 

查看线程数:

使用threading.enumerate()函数即可以看到当前线程的数量。安全

查看当前线程的名字:

使用threading.current_thread()能够看到当前线程的信息。网络

继承自threading.Thread类:

为了让线程代码更好的封装。可使用threading模块下的Thread类,继承自这个类,而后实现run方法,线程就会自动运行run方法中的代码。示例代码以下:多线程

import threading
import time

class CodingThread(threading.Thread):
    def run(self):
        for x in range(3):
            print('%s正在写代码' % threading.current_thread())
            time.sleep(1)

class DrawingThread(threading.Thread):
    def run(self):
        for x in range(3):
            print('%s正在画图' % threading.current_thread())
            time.sleep(1)

def multi_thread():
    t1 = CodingThread()
    t2 = DrawingThread()

    t1.start()
    t2.start()

if __name__ == '__main__':
    multi_thread()

 

多线程共享全局变量的问题:

多线程都是在同一个进程中运行的。所以在进程中的全局变量全部线程都是可共享的。这就形成了一个问题,由于线程执行的顺序是无序的。有可能会形成数据错误。好比如下代码:app

import threading

tickets = 0

def get_ticket():
    global tickets
    for x in range(1000000):
        tickets += 1
    print('tickets:%d'%tickets)

def main():
    for x in range(2):
        t = threading.Thread(target=get_ticket)
        t.start()

if __name__ == '__main__':
    main()

 

以上结果正常来说应该是6,可是由于多线程运行的不肯定性。所以最后的结果多是随机的。dom

锁机制:

为了解决以上使用共享全局变量的问题。threading提供了一个Lock类,这个类能够在某个线程访问某个变量的时候加锁,其余线程此时就不能进来,直到当前线程处理完后,把锁释放了,其余线程才能进来处理。示例代码以下:ide

import threading

VALUE = 0

gLock = threading.Lock()

def add_value():
    global VALUE
    gLock.acquire()
    for x in range(1000000):
        VALUE += 1
    gLock.release()
    print('value:%d'%VALUE)

def main():
    for x in range(2):
        t = threading.Thread(target=add_value)
        t.start()

if __name__ == '__main__':
    main()

 

Lock版本生产者和消费者模式:

生产者和消费者模式是多线程开发中常常见到的一种模式。生产者的线程专门用来生产一些数据,而后存放到一个中间的变量中。消费者再从这个中间的变量中取出数据进行消费。可是由于要使用中间变量,中间变量常常是一些全局变量,所以须要使用锁来保证数据完整性。如下是使用threading.Lock锁实现的“生产者与消费者模式”的一个例子:函数

import threading
import random
import time

gMoney = 1000
gLock = threading.Lock()
# 记录生产者生产的次数,达到10次就再也不生产
gTimes = 0

class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gLock
        global gTimes
        while True:
            money = random.randint(100, 1000)
            gLock.acquire()
            # 若是已经达到10次了,就再也不生产了
            if gTimes >= 10:
                gLock.release()
                break
            gMoney += money
            print('%s当前存入%s元钱,剩余%s元钱' % (threading.current_thread(), money, gMoney))
            gTimes += 1
            time.sleep(0.5)
            gLock.release()

class Consumer(threading.Thread):
    def run(self):
        global gMoney
        global gLock
        global gTimes
        while True:
            money = random.randint(100, 500)
            gLock.acquire()
            if gMoney > money:
                gMoney -= money
                print('%s当前取出%s元钱,剩余%s元钱' % (threading.current_thread(), money, gMoney))
                time.sleep(0.5)
            else:
                # 若是钱不够了,有多是已经超过了次数,这时候就判断一下
                if gTimes >= 10:
                    gLock.release()
                    break
                print("%s当前想取%s元钱,剩余%s元钱,不足!" % (threading.current_thread(),money,gMoney))
            gLock.release()

def main():
    for x in range(5):
        Consumer(name='消费者线程%d'%x).start()

    for x in range(5):
        Producer(name='生产者线程%d'%x).start()

if __name__ == '__main__':
    main()

 

Condition版的生产者与消费者模式:

Lock版本的生产者与消费者模式能够正常的运行。可是存在一个不足,在消费者中,老是经过while True死循环而且上锁的方式去判断钱够不够。上锁是一个很耗费CPU资源的行为。所以这种方式不是最好的。还有一种更好的方式即是使用threading.Condition来实现。threading.Condition能够在没有数据的时候处于阻塞等待状态。一旦有合适的数据了,还可使用notify相关的函数来通知其余处于等待状态的线程。这样就能够不用作一些无用的上锁和解锁的操做。能够提升程序的性能。首先对threading.Condition相关的函数作个介绍,threading.Condition相似threading.Lock,能够在修改全局数据的时候进行上锁,也能够在修改完毕后进行解锁。如下将一些经常使用的函数作个简单的介绍:

  1. acquire:上锁。
  2. release:解锁。
  3. wait:将当前线程处于等待状态,而且会释放锁。能够被其余线程使用notifynotify_all函数唤醒。被唤醒后会继续等待上锁,上锁后继续执行下面的代码。
  4. notify:通知某个正在等待的线程,默认是第1个等待的线程。
  5. notify_all:通知全部正在等待的线程。notifynotify_all不会释放锁。而且须要在release以前调用。

Condition版的生产者与消费者模式代码以下:

import threading
import random
import time

gMoney = 1000
gCondition = threading.Condition()
gTimes = 0
gTotalTimes = 5

class Producer(threading.Thread):
    def run(self):
        global gMoney
        global gCondition
        global gTimes
        while True:
            money = random.randint(100, 1000)
            gCondition.acquire()
            if gTimes >= gTotalTimes:
                gCondition.release()
                print('当前生产者总共生产了%s次'%gTimes)
                break
            gMoney += money
            print('%s当前存入%s元钱,剩余%s元钱' % (threading.current_thread(), money, gMoney))
            gTimes += 1
            time.sleep(0.5)
            gCondition.notify_all()
            gCondition.release()

class Consumer(threading.Thread):
    def run(self):
        global gMoney
        global gCondition
        while True:
            money = random.randint(100, 500)
            gCondition.acquire()
            # 这里要给个while循环判断,由于等轮到这个线程的时候
            # 条件有可能又不知足了
            while gMoney < money:
                if gTimes >= gTotalTimes:
                    gCondition.release()
                    return
                print('%s准备取%s元钱,剩余%s元钱,不足!'%(threading.current_thread(),money,gMoney))
                gCondition.wait()
            gMoney -= money
            print('%s当前取出%s元钱,剩余%s元钱' % (threading.current_thread(), money, gMoney))
            time.sleep(0.5)
            gCondition.release()

def main():
    for x in range(5):
        Consumer(name='消费者线程%d'%x).start()

    for x in range(2):
        Producer(name='生产者线程%d'%x).start()

if __name__ == '__main__':
    main()

 

Queue线程安全队列:

在线程中,访问一些全局变量,加锁是一个常常的过程。若是你是想把一些数据存储到某个队列中,那么Python内置了一个线程安全的模块叫作queue模块。Python中的queue模块中提供了同步的、线程安全的队列类,包括FIFO(先进先出)队列Queue,LIFO(后入先出)队列LifoQueue。这些队列都实现了锁原语(能够理解为原子操做,即要么不作,要么都作完),可以在多线程中直接使用。可使用队列来实现线程间的同步。相关的函数以下:

  1. 初始化Queue(maxsize):建立一个先进先出的队列。
  2. qsize():返回队列的大小。
  3. empty():判断队列是否为空。
  4. full():判断队列是否满了。
  5. get():从队列中取最后一个数据。
  6. put():将一个数据放到队列中。

使用生产者与消费者模式多线程下载表情包:

import threading
import requests
from lxml import etree
from urllib import request
import os
import re
from queue import Queue

class Producer(threading.Thread):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
    }
    def __init__(self,page_queue,img_queue,*args,**kwargs):
        super(Producer, self).__init__(*args,**kwargs)
        self.page_queue = page_queue
        self.img_queue = img_queue


    def run(self):
        while True:
            if self.page_queue.empty():
                break
            url = self.page_queue.get()
            self.parse_page(url)

    def parse_page(self,url):
        response = requests.get(url,headers=self.headers)
        text = response.text
        html = etree.HTML(text)
        imgs = html.xpath("//div[@class='page-content text-center']//a//img")
        for img in imgs:
            if img.get('class') == 'gif':
                continue
            img_url = img.xpath(".//@data-original")[0]
            suffix = os.path.splitext(img_url)[1]
            alt = img.xpath(".//@alt")[0]
            alt = re.sub(r'[,。??,/\\·]','',alt)
            img_name = alt + suffix
            self.img_queue.put((img_url,img_name))

class Consumer(threading.Thread):
    def __init__(self,page_queue,img_queue,*args,**kwargs):
        super(Consumer, self).__init__(*args,**kwargs)
        self.page_queue = page_queue
        self.img_queue = img_queue

    def run(self):
        while True:
            if self.img_queue.empty() and self.page_queue.empty():
              break
            img_url,filename = self.img_queue.get()
            request.urlretrieve(url,'images/'+filename)
            print(filename+'  下载完成!')

def main():
    page_queue = Queue(100)
    img_queue = Queue(500)
    for x in range(1,101):
        url = "http://www.doutula.com/photo/list/?page=%d" % x
        page_queue.put(url)

    for x in range(5):
        t = Producer(page_queue,img_queue)
        t.start()

    for x in range(5):
        t = Consumer(page_queue,img_queue)
        t.start()

if __name__ == '__main__':
    main()

 

GIL全局解释器锁:

Python自带的解释器是CPythonCPython解释器的多线程其实是一个假的多线程(在多核CPU中,只能利用一核,不能利用多核)。同一时刻只有一个线程在执行,为了保证同一时刻只有一个线程在执行,在CPython解释器中有一个东西叫作GIL(Global Intepreter Lock),叫作全局解释器锁。这个解释器锁是有必要的。由于CPython解释器的内存管理不是线程安全的。固然除了CPython解释器,还有其余的解释器,有些解释器是没有GIL锁的,见下面:

  1. Jython:用Java实现的Python解释器。不存在GIL锁。更多详情请见:https://zh.wikipedia.org/wiki/Jython
  2. IronPython:用.net实现的Python解释器。不存在GIL锁。更多详情请见:https://zh.wikipedia.org/wiki/IronPython
  3. PyPy:用Python实现的Python解释器。存在GIL锁。更多详情请见:https://zh.wikipedia.org/wiki/PyPy
    GIL虽然是一个假的多线程。可是在处理一些IO操做(好比文件读写和网络请求)仍是能够在很大程度上提升效率的。在IO操做上建议使用多线程提升效率。在一些CPU计算操做上不建议使用多线程,而建议使用多进程。

多线程下载百思不得姐段子:

import requests
from lxml import etree
import threading
from queue import Queue
import csv


class BSSpider(threading.Thread):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
    }
    def __init__(self,page_queue,joke_queue,*args,**kwargs):
        super(BSSpider, self).__init__(*args,**kwargs)
        self.base_domain = 'http://www.budejie.com'
        self.page_queue = page_queue
        self.joke_queue = joke_queue

    def run(self):
        while True:
            if self.page_queue.empty():
                break
            url = self.page_queue.get()
            response = requests.get(url, headers=self.headers)
            text = response.text
            html = etree.HTML(text)
            descs = html.xpath("//div[@class='j-r-list-c-desc']")
            for desc in descs:
                jokes = desc.xpath(".//text()")
                joke = "\n".join(jokes).strip()
                link = self.base_domain+desc.xpath(".//a/@href")[0]
                self.joke_queue.put((joke,link))
            print('='*30+"第%s页下载完成!"%url.split('/')[-1]+"="*30)

class BSWriter(threading.Thread):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
    }

    def __init__(self, joke_queue, writer,gLock, *args, **kwargs):
        super(BSWriter, self).__init__(*args, **kwargs)
        self.joke_queue = joke_queue
        self.writer = writer
        self.lock = gLock

    def run(self):
        while True:
            try:
                joke_info = self.joke_queue.get(timeout=40)
                joke,link = joke_info
                self.lock.acquire()
                self.writer.writerow((joke,link))
                self.lock.release()
                print('保存一条')
            except:
                break

def main():
    page_queue = Queue(10)
    joke_queue = Queue(500)
    gLock = threading.Lock()
    fp = open('bsbdj.csv', 'a',newline='', encoding='utf-8')
    writer = csv.writer(fp)
    writer.writerow(('content', 'link'))

    for x in range(1,11):
        url = 'http://www.budejie.com/text/%d' % x
        page_queue.put(url)

    for x in range(5):
        t = BSSpider(page_queue,joke_queue)
        t.start()

    for x in range(5):
        t = BSWriter(joke_queue,writer,gLock)
        t.start()

if __name__ == '__main__':
    main()
相关文章
相关标签/搜索