爬虫_古诗文网(队列,多线程,锁,正则,xpath)
import requests
from queue import Queue
import threading
from lxml import etree
import re
import csv class Producer(threading.Thread):
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'}
def __init__(self, page_queue, poem_queue, *args, **kwargs):
super(Producer, self).__init__(*args, **kwargs)
self.page_queue = page_queue
self.poem_queue = poem_queue def run(self):
while True:
if self.page_queue.empty():
break
url = self.page_queue.get()
self.parse_html(url) def parse_html(self, url):
# poems = []
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'}
response = requests.get(url, headers=headers)
response.raise_for_status()
html = response.text
html_element = etree.HTML(html)
titles = html_element.xpath('//div[@class="cont"]//b/text()')
contents = html_element.xpath('//div[@class="contson"]')
hrefs = html_element.xpath('//div[@class="cont"]/p[1]/a/@href')
for index, content in enumerate(contents):
title = titles[index]
content = etree.tostring(content, encoding='utf-8').decode('utf-8')
content = re.sub(r'<.*?>|\n|', '', content)
content = re.sub(r'\u3000\u3000', '', content)
content = content.strip()
href = hrefs[index]
self.poem_queue.put((title, content, href)) class Consumer(threading.Thread): def __init__(self, poem_queue, writer, gLock, *args, **kwargs):
super(Consumer, self).__init__(*args, **kwargs)
self.writer = writer
self.poem_queue = poem_queue
self.lock = gLock def run(self):
while True:
try:
title, content, href = self.poem_queue.get(timeout=20)
self.lock.acquire()
self.writer.writerow((title, content, href))
self.lock.release()
except:
break def main():
page_queue = Queue(100)
poem_queue = Queue(500)
gLock = threading.Lock()
fp = open('poem.csv', 'a',newline='', encoding='utf-8')
writer = csv.writer(fp)
writer.writerow(('title', 'content', 'href')) for x in range(1, 100):
url = 'https://www.gushiwen.org/shiwen/default.aspx?page=%d&type=0&id=0' % x
page_queue.put(url) for x in range(5):
t = Producer(page_queue, poem_queue)
t.start() for x in range(5):
t = Consumer(poem_queue, writer, gLock)
t.start() if __name__ == '__main__':
main()
运行结果

爬虫_古诗文网(队列,多线程,锁,正则,xpath)的更多相关文章
- 爬虫_中国天气网_文字天气预报(xpath)
import requests from lxml import etree headers = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/5 ...
- requests_cookie登陆古诗文网。session的使用
通过登录失败,快速找到登录接口 获取hidden隐藏域中的id的value值 # 通过登陆 然后进入到主页面 # 通过找登陆接口我们发现 登陆的时候需要的参数很多 # _VIEWSTATE: /m1O ...
- 爬虫_豆瓣全部正在热映电影 (xpath)
单纯地练习一下xpath import requests from lxml import etree def get_url(url): html = requests.get(url) retur ...
- Python爬虫入门教程 11-100 行行网电子书多线程爬取
行行网电子书多线程爬取-写在前面 最近想找几本电子书看看,就翻啊翻,然后呢,找到了一个 叫做 周读的网站 ,网站特别好,简单清爽,书籍很多,而且打开都是百度网盘可以直接下载,更新速度也还可以,于是乎, ...
- 初识python 之 爬虫:使用正则表达式爬取“古诗文”网页数据
通过requests.re(正则表达式) 爬取"古诗文"网页数据. 详细代码如下: #!/user/bin env python # author:Simple-Sir # tim ...
- Java多线程--锁的优化
Java多线程--锁的优化 提高锁的性能 减少锁的持有时间 一个线程如果持有锁太长时间,其他线程就必须等待相应的时间,如果有多个线程都在等待该资源,整体性能必然下降.所有有必要减少单个线程持有锁的时间 ...
- synchronized与static synchronized 的差别、synchronized在JVM底层的实现原理及Java多线程锁理解
本Blog分为例如以下部分: 第一部分:synchronized与static synchronized 的差别 第二部分:JVM底层又是怎样实现synchronized的 第三部分:Java多线程锁 ...
- Python爬虫爬取全书网小说,程序源码+程序详细分析
Python爬虫爬取全书网小说教程 第一步:打开谷歌浏览器,搜索全书网,然后再点击你想下载的小说,进入图一页面后点击F12选择Network,如果没有内容按F5刷新一下 点击Network之后出现如下 ...
- SANSA 上上洛可可 贾伟作品 高山流水 香炉 香插香台香具 高端商务礼品 黑色【正品 价格 图片 折扣 评论】_尚品网ShangPin.com
SANSA 上上洛可可 贾伟作品 高山流水 香炉 香插香台香具 高端商务礼品 黑色[正品 价格 图片 折扣 评论]_尚品网ShangPin.com
随机推荐
- Python_装饰器精讲_33
from functools import wraps def wrapper(func): #func = holiday @wraps(func) def inner(*args,**kwargs ...
- H5 26-CSS三大特性之优先级
26-CSS三大特性之优先级 类>标签>通配符>继承>浏览器默认 --> 0 我是段落 <!DOCTYPE html> <html lang=" ...
- 行政区划sql数据脚本
行政区划sql数据脚本 IF (EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TB_Province]') ...
- 【学习总结】GirlsInAI ML-diary day-5-布尔表达式/Bool
[学习总结]GirlsInAI ML-diary 总 原博github链接-day5 认识布尔表达式 简单来说,bool 就是对错判断. 给个条件,如果满足条件就返回True, 不满足条件就返回Fal ...
- Nginx三部曲(2)性能
我们会告诉你 Nginx 如何工作及其背后的理念,还有如何优化以加快应用的性能,如何安装启动和保持运行. 这个教程有三个部分: 基本概念 —— 这部分需要去了解 Nginx 的一些指令和使用场景,继承 ...
- [官网]Linux版本历史
This is a list of links to every changelog. https://kernelnewbies.org/LinuxVersions 总结一下 2.6.x 存在了八年 ...
- [官网]Red Hat Enterprise Linux Release Dates
Red Hat Enterprise Linux Release Dates https://access.redhat.com/articles/3078 The tables below list ...
- 免费苹果账号(apple id)申请ios证书p12真机调试
HBuilder可以直接打包越狱版的ipa包,但需要越狱手机才能安装,如果需要安装到没越狱的手机安装,需要自己申请ios证书打包. 一般是需要一个付费了的苹果开发者账号才能申请ios证书打包. 这里介 ...
- ArrayList的扩容机制
一.ArrayList的扩容机制 1.扩容的计算方式是向右位移,即:newSize = this.size + (this.size>>1).向右位移,只有在当前值为偶数时,才是除以2:奇 ...
- mac 中登陆mysql忘记密码解决办法
1.打开终端,输入命令:cd /usr/local/mysql/bin 2.mysql -uroot -p,用这条命令登陆时报错信息: 报错:Enter password: ERROR 1045 (2 ...