IE9useragenth和多线程爬取

IE 9的useragent:'User-Agent':'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0);'

每个useragent发送请求服务器返回的信息可能不同,但是用IE 9的useragent  大部分都是相同的

一个进程的内存空间是共享的,每个进程里的线程都可以使用这个共享空间,一个线程在使用这个共享的时候,其他线程必须等它结束

通过‘锁’实现,作用就是防止多个线程使用这快内存空间。先使用的线程会将空间上锁,其他线程就在门口等待,打开锁在进去

GIL:Python里的执行通行证,而且只有一个。拿到通行证的线程就可以进入CPU。没有就等着

Python的多线程适用于:大量密集的I/O处理

Python 多线程:大量的密集并行计算

多线程爬取糗事百科:

import threading

from queue import Queue
#解析库
from lxml import etree
#请求处理
import requests

import json

#定义解析多线程
class ThreadParse(threading.Thread):
    def __init__(self,threadName,dataQueue,filename):
        #调用父类的初始化
        super(ThreadParse,self).__init__()
        #线程名
        self.threadName=threadName
        #数据队列
        self.dataQueue=dataQueue
        #保存解析后数据的文件名
        self.filename=filename

        self.headers={'User-Agent':'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'}
    def run(self):
        while not  PARSE_EXIT:
            try:
                html=self.dataQueue.get(False)
                self.parse(html)
            except:
                pass
        # print('结束'+self.threadName)
    def parse(self,html):
        html=etree.HTML(html)
        node_list = text.xpath('//div[contains(@id, "qiushi_tag")]')

        items = {}
        for node in node_list:
            # xpath返回的列表,这个列表就这一个参数,用索引方式取出来,用户名
            username = node.xpath('./div/a/@title')[0]
            # 图片连接
            image = node.xpath('.//div[@class="thumb"]//@src')  # [0]
            # 取出标签下的内容,段子内容
            content = node.xpath('.//div[@class="content"]/span')[0].text
            # 取出标签里包含的内容,点赞
            zan = node.xpath('.//i')[0].text
            # 评论
            comments = node.xpath('.//i')[1].text

            items = {
                "username": username,
                "image": image,
                "content": content,
                "zan": zan,
                "comments": comments
            }

            with open("qiushi.json", "a") as f:
                f.write(json.dumps(items, ensure_ascii=False).encode("utf-8"))

 #定义采集多线程
class ThreadCrawl(threading.Thread):       #ThreadCrawl(threadName,pageQueue,dataQueue)
    def __init__(self,threadName,pageQueue,dataQueue):
        #调用父类的初始化
        super(ThreadCrawl,self).__init__()
        #线程名
        self.threadName=threadName
        #页码队列
        self.pageQueue=pageQueue
        #数据队列
        self.dataQueue=dataQueue

        self.headers={'User-Agent':'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'}
    def run(self):
        #弄个循环一直做采集,当页码队列为空时就采集完了
        print('启动'+self.threadName)
        while not CRAWL_EXIT:
            try:
            #取出一个数字,先进先出
            #可选参数block,默认值为True
            #1.如果队列为空,block为True的话,不会结束,会进入阻塞状态,直到队列有新的数据
            #2.如果队列为空,block为False的话,就弹出一个Queue.empty()异常
                page=self.pageQueue.get(False)
                print('采集了第'+page)
                url='http://www.qiushibaike.com/8hr/page/'+str(page)+'/'
                content=requests.get(url,headers=self.headers)
            # 把采集到的 页面源码放入数据队列中
                self.dataQueue.put(content)
            except:
                pass
        print('结束'+self.threadName)



CRAWL_EXIT=False
PARSE_EXIT=False


def main():

    #页码的队列,表示可以存10个值,不写就是无限多个
    pageQueue=Queue(10)
    #放入1-10的数字,先进先出
    for i in range(1,11):
        #在队列中放入10个数
        pageQueue.put(i)


    #采集每页html的源码的数据队列
    dataQueue=Queue()

    filename=open('qiushi.json','a')

    #三个采集线程的名字
    crawllist=['采集线程1号','采集线程2号','采集线程3号']
    #存储三个采集线程
    threadcrawl=[]
    for threadName in crawllist:
        thread=ThreadCrawl(threadName,pageQueue,dataQueue)
        #线程的对象执行的时候调用start()方法,对应是线程类(函数)里的run方法
        thread.start()
        threadcrawl.append(thread)
    #三个解析线程的名字
    parseList=['解析线程1号','解析线程2号','解析线程3号']
    #存储三个解析线程
    threadparse=[]
    for threadName in parseList:
        thread=ThreadParse(threadName,dataQueue,filename)
        thread.start()
        threadparse.append(thread)

    #等待pageQueue队列为空,也就是等待之前的操作执行完毕
    while  not pageQueue.empty():
        pass
    #如果pageQueue为空,采集线程退出循环
    global CRAWL_EXIT
    CRAWL_EXIT=True

    print("pageQueue为空")
    #防止守护线程发生,加个阻塞   .json
    for thread in threadcrawl:
        thread.join()
        print('1')


if __name__=='__main__':
    main()

猜你喜欢

转载自blog.csdn.net/weixin_42166745/article/details/82952204