爬虫_古诗文网(队列,多线程,锁,正则,xpath)

本文介绍了一个使用Python实现的多线程爬虫程序,该程序能够从古诗文网抓取诗歌标题、内容及链接,并将其保存到CSV文件中。通过Requests、lxml和正则表达式等技术解析网页,利用队列和线程管理抓取过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

 1 import requests
 2 from queue import Queue
 3 import threading
 4 from lxml import etree
 5 import re
 6 import csv
 7 
 8 
 9 class Producer(threading.Thread):
10     headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'}
11     def __init__(self, page_queue, poem_queue, *args, **kwargs):
12         super(Producer, self).__init__(*args, **kwargs)
13         self.page_queue = page_queue
14         self.poem_queue = poem_queue
15 
16 
17     def run(self):
18         while True:
19             if self.page_queue.empty():
20                 break
21             url = self.page_queue.get()
22             self.parse_html(url)
23 
24 
25     def parse_html(self, url):
26         # poems = []
27         headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'}
28         response = requests.get(url, headers=headers)
29         response.raise_for_status()
30         html = response.text
31         html_element = etree.HTML(html)
32         titles = html_element.xpath('//div[@class="cont"]//b/text()')
33         contents = html_element.xpath('//div[@class="contson"]')
34         hrefs = html_element.xpath('//div[@class="cont"]/p[1]/a/@href')
35         for index, content in enumerate(contents):
36             title = titles[index]
37             content = etree.tostring(content, encoding='utf-8').decode('utf-8')
38             content = re.sub(r'<.*?>|\n|', '', content)
39             content = re.sub(r'\u3000\u3000', '', content)
40             content = content.strip()
41             href = hrefs[index]
42             self.poem_queue.put((title, content, href))
43 
44 
45 class Consumer(threading.Thread):
46 
47     def __init__(self, poem_queue, writer, gLock, *args, **kwargs):
48         super(Consumer, self).__init__(*args, **kwargs)
49         self.writer = writer
50         self.poem_queue = poem_queue
51         self.lock = gLock
52 
53     def run(self):
54         while True:
55             try:
56                 title, content, href = self.poem_queue.get(timeout=20)
57                 self.lock.acquire()
58                 self.writer.writerow((title, content, href))
59                 self.lock.release()
60             except:
61                 break
62 
63 
64 def main():
65     page_queue = Queue(100)
66     poem_queue = Queue(500)
67     gLock = threading.Lock()
68     fp = open('poem.csv', 'a',newline='', encoding='utf-8')
69     writer = csv.writer(fp)
70     writer.writerow(('title', 'content', 'href'))
71    
72 
73     for x in range(1, 100):
74         url = 'https://www.gushiwen.org/shiwen/default.aspx?page=%d&type=0&id=0' % x
75         page_queue.put(url)
76 
77     for x in range(5):
78         t = Producer(page_queue, poem_queue)
79         t.start()
80 
81     for x in range(5):
82         t = Consumer(poem_queue, writer, gLock)
83         t.start()
84 
85 if __name__ == '__main__':
86     main()

运行结果

 

转载于:https://www.cnblogs.com/MC-Curry/p/9460507.html

【为什么学爬虫?】        1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到!        2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是:络请求:模拟浏览器的行为从上抓取数据。数据解析:将请求下来的数据进行过滤,提取我们想要的数据。数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是:爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态爬虫、字体反爬识别等。Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。通过爬虫进阶的知识点我们能应付大量的反爬站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求!【课程服务】 专属付费社群+定期答疑
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值