Python3爬虫多线程+xpath实现

多线程爬取糗事百科段子

from threading import Thread
from queue import Queue
import requests
from fake_useragent import UserAgent
from lxml import etree

class CrawlInfo(Thread):
    def __init__(self,url_queue,html_queue):
        Thread.__init__(self)
        self.url_queue=url_queue
        self.html_queue=html_queue
    def run(self):
        headers = {
            'User-Agent': UserAgent().chrome
        }
        while not self.url_queue.empty():
            response=requests.get(self.url_queue.get(),headers=headers)
            if response.status_code==200:
                # print(response.text)
                return html_queue.put(response.text)

class ParseInfo(Thread):
    def __init__(self,html_queue):
        Thread.__init__(self)

        self.html_queue = html_queue

    def run(self):
        print(html_queue)
        while not self.html_queue.empty():
            e=etree.HTML(self.html_queue.get())
            span_contents=e.xpath('//div[@class="content"]/span[1]')
            with open('段子.txt','a',encoding='utf-8') as f:
                for span in span_contents:
                    info=span.xpath('string(.)')
                    # print(info)
                    f.write(info+'\n')

if __name__ == '__main__':
    url_queue = Queue()
    html_queue=Queue()
    base_url = 'https://www.qiushibaike.com/text/page/{}/'
    for i in range(1, 10):
        new_url = base_url.format(i)
        url_queue.put(new_url)
    crawlList=[]
    for i in range(3):
        c=CrawlInfo(url_queue,html_queue)
        crawlList.append(c)
        c.start()
    for crawl in crawlList:
        crawl.join()

    p=ParseInfo(html_queue)
    p.start()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值