20.multi_协程方法抓取总阅读量
# 用asyncio和aiohttp抓取博客的总阅读量 (提示:先用接又找到每篇文章的链接)
# https://www.jianshu.com/u/130f76596b02
import re
import asyncio
import aiohttp
import requests
import ssl
from lxml import etree
from asyncio.queues import Queue
from aiosocksy import Socks5Auth
from aiosocksy.connector import ProxyConnector, ProxyClientRequest
class Common():
task_queue = Queue()
result_queue = Queue()
result_queue_1 = []
async def session_get(session, url, socks):
auth = Socks5Auth(login='...', password='...')
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
timeout = aiohttp.ClientTimeout(total=20)
response = await session.get(
url,
proxy=socks,
proxy_auth=auth,
timeout=timeout,
headers=headers,
ssl=ssl.SSLContext()
)
return await response.text(), response.status
async def download(url):
connector = ProxyConnector()
socks = None
async with aiohttp.ClientSession(
connector=connector,
request_class=ProxyClientRequest
) as session:
ret, status = await session_get(session, url, socks)
if 'window.location.href' in ret and len(ret) < 1000:
url = ret.split("window.location.href='")[1].split("'")[0]
ret, status = await session_get(session, url, socks)
return ret, status
async def parse_html(content):
read_num_pattern = re.compile(r'"views_count":\d+')
read_num = int(read_num_pattern.findall(content)[0].split(':')[-1])
return read_num
def get_all_article_links():
links_list = []
for i in range(1, 21):
url = 'https://www.jianshu.com/u/130f76596b02?order_by=shared_at&page={}'.format(
i)
header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get(url,
headers=header,
timeout=5
)
tree = etree.HTML(response.text)
article_links = tree.xpath(
'//div[@class="content"]/a[@class="title"]/@href')
for item in article_links:
article_link = 'https://www.jianshu.com' + item
links_list.append(article_link)
print(article_link)
return links_list
async def down_and_parse_task(queue):
while True:
try:
url = queue.get_nowait()
except BaseException:
return
error = None
for retry_cnt in range(3):
try:
html, status = await download(url)
if status != 200:
html, status = await download(url)
read_num = await parse_html(html)
print(read_num)
# await Common.result_queue.put(read_num)
Common.result_queue_1.append(read_num)
break
except Exception as e:
error = e
await asyncio.sleep(0.2)
continue
else:
raise error
async def count_sum():
while True:
try:
print(Common.result_queue_1)
print('总阅读量 = ', sum(Common.result_queue_1))
await asyncio.sleep(3)
except BaseException:
pass
async def main():
all_links = get_all_article_links()
for item in set(all_links):
await Common.task_queue.put(item)
for _ in range(10):
loop.create_task(down_and_parse_task(Common.task_queue))
loop.create_task(count_sum())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()
20.multi_协程方法抓取总阅读量的更多相关文章
- 代理池抓取基础版-(python协程)--抓取网站(西刺-后期会持续更新)
# coding = utf- __autor__ = 'litao' import urllib.request import urllib.request import urllib.error ...
- 成功抓取csdn阅读量过万博文
http://images.cnblogs.com/cnblogs_com/elesos/1120632/o_111.png var commentscount = 1; 嵌套的评论算一条,这个可能有 ...
- 比物理线程都好用的C++20的协程,你会用吗?
摘要:事件驱动(event driven)是一种常见的代码模型,其通常会有一个主循环(mainloop)不断的从队列中接收事件,然后分发给相应的函数/模块处理.常见使用事件驱动模型的软件包括图形用户界 ...
- 开启gzip压缩/cdn是否会影响抓取和收录量
http://www.wocaoseo.com/thread-291-1-1.html 服务器开启gzip压缩是否会影响蜘蛛抓取和收录量?站点开了CDN,对百度SEO影响有多大?我发现我们站自从开了C ...
- (20)gevent协程
协程: 也叫纤程,协程是线程的一种实现,指的是一条线程能够在多任务之间来回切换的一 种实现,对于CPU.操作系统来说,协程并不存在 任务之间的切换会花费时间.目前电脑配置一般线程开到200会阻塞卡顿 ...
- scrapy实战4 GET方法抓取ajax动态页面(以糗事百科APP为例子):
一般来说爬虫类框架抓取Ajax动态页面都是通过一些第三方的webkit库去手动执行html页面中的js代码, 最后将生产的html代码交给spider分析.本篇文章则是通过利用fiddler抓包获取j ...
- scrapy实战5 POST方法抓取ajax动态页面(以慕课网APP为例子):
在手机端打开慕课网,fiddler查看如图注意圈起来的位置 经过分析只有画线的page在变化 上代码: items.py import scrapy class ImoocItem(scrapy.It ...
- ADB logcat 过滤方法(抓取日志)
1. Log信息级别 Log.v- VERBOSE : 黑色 Log.d- DEBUG : 蓝色 Log.i- INFO : 绿色 Log.w- WARN : 橙色 Log.e- ERROR ...
- python3用BeautifulSoup用字典的方法抓取a标签内的数据
# -*- coding:utf-8 -*- #python 2.7 #XiaoDeng #http://tieba.baidu.com/p/2460150866 #标签操作 from bs4 imp ...
随机推荐
- 好久没写题解了= =这次是bzoj 1051
唉= =这道题我都想到了tarjan缩点,但是没有想到最后一步啊= =我们很容易想到反向建边然后缩点,这时候我们看由多少个联通块的入度为0,如果为1个,那就输出这个块的大小,否则输出0: #inclu ...
- kafka集群安装和使用
kafka(1)kafka是一个分布式的消息缓存系统(2)kafka集群中的服务器都叫做broker(3)kafka有两类客户端,一个叫做producer(消息生产者),一类叫做consumer(消息 ...
- NX二次开发-算法篇-vector函数排序(例子:遍历所有点并排序)
NX9+VS2012 #include <uf.h> #include <uf_ui.h> #include <uf_curve.h> #include <u ...
- ionic-CSS:ionic 网格(Grid)
ylbtech-ionic-CSS:ionic 网格(Grid) 1.返回顶部 1. ionic 网格(Grid) ionic 的网格(Grid)和其他大部分框架有所不同,它采用了弹性盒子模型(Fle ...
- JavaScript笔记 - Object对象特性的应用
可以依据js对象中key是永远不会重复的原则,来模拟Map类型以及去除数组重复项. 1.模拟Map类型 (1)构造Map对象 function Map(){ //private var obj = { ...
- OSI七层网络模型分别是哪七层?各运行那些协议?
本文摘自:https://blog.csdn.net/JeremyZJM/article/details/78184775 应用层 DHCP · DNS · FTP · Gopher · HTTP · ...
- java could not open `C|D|E|F:\jre\lib\amd64\jvm.cfg' 解决方案与原因
因为安装了 jdk 后发现有多个 jre 一个是安装目录下的. 还有一个是安装后的自动安装的注意路径都不一样. 由于本人有强迫症所有不能容忍有两个 jre 目录的存在,所以果断删除了 D 盘下的.谨慎 ...
- code rain???
Everybody loves the visual effect of the falling binary code known as ” Rain ” in The Matrix. In thi ...
- solr 启动报错Cannot load analyzer: org.wltea.analyzer.lucene.IKAnalyzer
schema.xml 配置文件信息: <field name="title" type="text_ik" indexed="true" ...
- IntelliJ IDEA无法创建springboot项目解决办法
最佳解决办法:IntelliJ IDEA---右键---以管理员身份运行. 方法二: 1.打开控制面板--系统和安全--windows防火墙 2.找到自己的默认浏览器,打勾,这里是谷歌浏览器 3.打开 ...