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)的更多相关文章

  1. 爬虫_中国天气网_文字天气预报(xpath)

    import requests from lxml import etree headers = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/5 ...

  2. requests_cookie登陆古诗文网。session的使用

    通过登录失败,快速找到登录接口 获取hidden隐藏域中的id的value值 # 通过登陆 然后进入到主页面 # 通过找登陆接口我们发现 登陆的时候需要的参数很多 # _VIEWSTATE: /m1O ...

  3. 爬虫_豆瓣全部正在热映电影 (xpath)

    单纯地练习一下xpath import requests from lxml import etree def get_url(url): html = requests.get(url) retur ...

  4. Python爬虫入门教程 11-100 行行网电子书多线程爬取

    行行网电子书多线程爬取-写在前面 最近想找几本电子书看看,就翻啊翻,然后呢,找到了一个 叫做 周读的网站 ,网站特别好,简单清爽,书籍很多,而且打开都是百度网盘可以直接下载,更新速度也还可以,于是乎, ...

  5. 初识python 之 爬虫:使用正则表达式爬取“古诗文”网页数据

    通过requests.re(正则表达式) 爬取"古诗文"网页数据. 详细代码如下: #!/user/bin env python # author:Simple-Sir # tim ...

  6. Java多线程--锁的优化

    Java多线程--锁的优化 提高锁的性能 减少锁的持有时间 一个线程如果持有锁太长时间,其他线程就必须等待相应的时间,如果有多个线程都在等待该资源,整体性能必然下降.所有有必要减少单个线程持有锁的时间 ...

  7. synchronized与static synchronized 的差别、synchronized在JVM底层的实现原理及Java多线程锁理解

    本Blog分为例如以下部分: 第一部分:synchronized与static synchronized 的差别 第二部分:JVM底层又是怎样实现synchronized的 第三部分:Java多线程锁 ...

  8. Python爬虫爬取全书网小说,程序源码+程序详细分析

    Python爬虫爬取全书网小说教程 第一步:打开谷歌浏览器,搜索全书网,然后再点击你想下载的小说,进入图一页面后点击F12选择Network,如果没有内容按F5刷新一下 点击Network之后出现如下 ...

  9. SANSA 上上洛可可 贾伟作品 高山流水 香炉 香插香台香具 高端商务礼品 黑色【正品 价格 图片 折扣 评论】_尚品网ShangPin.com

    SANSA 上上洛可可 贾伟作品 高山流水 香炉 香插香台香具 高端商务礼品 黑色[正品 价格 图片 折扣 评论]_尚品网ShangPin.com

随机推荐

  1. Python_动态参数、名称空间、作用域、作用域链、加载顺序、函数的嵌套、global、nonlocal

    1.动态参数 当实参数量与形参数量相等时,参数传递正常. def func1(a, b, c): pass func1(1, 2, 3) 当实参数量与形参数量不相等时,则会报错. def func1( ...

  2. rest-framework的权限组件

    权限组件 写在开头: 首先要在models表中添加一个用户类型的字段: class User(models.Model): name=models.CharField(max_length=32) p ...

  3. 多线程系列之三:Immutable 模式

    一,什么是Immutable模式?immutable就是不变的,不发生改变的.Immutable模式中存在着确保实例状态不发生变化改变的类.这些实例不需要互斥处理.String就是一个Immutabl ...

  4. vue 短信验证

    直接贴代码: HTML <div class="phone"> <div class="number"> <p class=&qu ...

  5. oninput事件和onchange事件区别

    onchange事件 触发条件:在域内容更改时触发,也可用于单选框和复选框改变后触发 作用对象:select.input.textarea oninput事件 触发条件:在域内容更改时触发(严格说在用 ...

  6. (C/C++)区别:数组与指针,指针与引用

    1.数组跟指针的区别 数组要么在静态存储区被创建(如全局数组),要么在栈上被创建.数组名对应着(而不是指向)一块内存,其地址与容量在生命期内保持不变,只有数组的内容可以改变. 指针可以随时指向任意类型 ...

  7. python之路--网络编程之socket

    一 . 网络编程 CS架构 客户端服务端架构 服务端:提供服务的 客户端:享受服务的 BS架构:浏览器和服务端 网络通信流程: 集线器:将所有连接上它的电脑全部联通起来 交换机:升级版的集线器 网卡: ...

  8. python之路-字符串

    一.类型转换 a = 10 print(type(a)) # <class 'int'> d = str(a) # 把数字转换成str print(type(d)) # <class ...

  9. Golang的日志处理

    整个看了一圈下来,感觉Golang的日志包在管理多线程安全的情况下,提供了最小粒度的工具.并没有提供什么复杂的过滤器之类的生成. 实现了一个demo来记录一下日志分类日志打印等实现: package ...

  10. k8s使用Glusterfs动态生成pv

    一.环境介绍 [root@k8s-m ~]# cat /etc/hosts127.0.0.1 localhost localhost.localdomain localhost4 localhost4 ...