多线程爬取糗事百科

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

class qiushi_threading():
    def __init__(self):
        self.url="http://www.qiushibaike.com/8hr/page/{}"
        self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"}
        self.url_queue=Queue()
        self.parse_queue=Queue()
        self.html_queue=Queue()
        self.content_list_queue=Queue()

    def get_url(self):
        for i in range(1,14):
            self.url_queue.put(self.url.format(i))


    def parse_url(self):
        url=self.url_queue.get()
        response=requests.get(url,self.headers)

        #如果响应不成功,则将url退回到队列中再次请求
        if response.status_code !=200:
            self.url_queue.put(url)
        else:
            self.html_queue.put(response.content.decode())
        #执行完一个任务,让url_queue队列的计数-1
        #task_done的含义:直接看queue.py中的注释。主要是给join用的,每次get后需要调用task_done,直到所有任务都task_done。join才取消阻塞
        self.url_queue.task_done()


    def get_content_list(self):
        html_str=self.html_queue.get()
        html=etree.HTML(html_str)
        div_list=html.xpath("//div[@id='content-left']/div")
        content_list=[]
        for div in div_list:
            item={}
            #字符串的strip()方法可以取出空格
            item['username']=div.xpath(".//h2/text()")[0].strip()
            item["content"] = [i.strip() for i in div.xpath(".//div[@class='content']/span/text()")]

    def run(self):
        #创建获取url子线程
        t_url=threading.Thread(target=self.get_url)
        t_url.setDaemon(True)
        t_url.start()

        #创建prase子线程
        t_parse=threading.Thread(target=self.parse_url)
        t_parse.setDaemon(True)
        t_parse.start()

        #创建提取数据子线程
        t_get=threading.Thread(target=self.get_content_list)
        t_get.setDaemon(True)
        t_get.start()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值