# 用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_协程方法抓取总阅读量的更多相关文章

  1. 代理池抓取基础版-(python协程)--抓取网站(西刺-后期会持续更新)

    # coding = utf- __autor__ = 'litao' import urllib.request import urllib.request import urllib.error ...

  2. 成功抓取csdn阅读量过万博文

    http://images.cnblogs.com/cnblogs_com/elesos/1120632/o_111.png var commentscount = 1; 嵌套的评论算一条,这个可能有 ...

  3. 比物理线程都好用的C++20的协程,你会用吗?

    摘要:事件驱动(event driven)是一种常见的代码模型,其通常会有一个主循环(mainloop)不断的从队列中接收事件,然后分发给相应的函数/模块处理.常见使用事件驱动模型的软件包括图形用户界 ...

  4. 开启gzip压缩/cdn是否会影响抓取和收录量

    http://www.wocaoseo.com/thread-291-1-1.html 服务器开启gzip压缩是否会影响蜘蛛抓取和收录量?站点开了CDN,对百度SEO影响有多大?我发现我们站自从开了C ...

  5. (20)gevent协程

    协程: 也叫纤程,协程是线程的一种实现,指的是一条线程能够在多任务之间来回切换的一 种实现,对于CPU.操作系统来说,协程并不存在 任务之间的切换会花费时间.目前电脑配置一般线程开到200会阻塞卡顿 ...

  6. scrapy实战4 GET方法抓取ajax动态页面(以糗事百科APP为例子):

    一般来说爬虫类框架抓取Ajax动态页面都是通过一些第三方的webkit库去手动执行html页面中的js代码, 最后将生产的html代码交给spider分析.本篇文章则是通过利用fiddler抓包获取j ...

  7. scrapy实战5 POST方法抓取ajax动态页面(以慕课网APP为例子):

    在手机端打开慕课网,fiddler查看如图注意圈起来的位置 经过分析只有画线的page在变化 上代码: items.py import scrapy class ImoocItem(scrapy.It ...

  8. ADB logcat 过滤方法(抓取日志)

    1. Log信息级别 Log.v- VERBOSE  : 黑色 Log.d- DEBUG  : 蓝色 Log.i- INFO  : 绿色 Log.w- WARN  : 橙色 Log.e- ERROR ...

  9. python3用BeautifulSoup用字典的方法抓取a标签内的数据

    # -*- coding:utf-8 -*- #python 2.7 #XiaoDeng #http://tieba.baidu.com/p/2460150866 #标签操作 from bs4 imp ...

随机推荐

  1. 27 string类中常用的方法列表

    1. 获取方法 int length()     获取字符串的长度 char charAt(int index) 获取特定位置的字符 (角标越界) int indexOf(String str) 获取 ...

  2. 【SPOJ DQUERY】区间数字统计

    [链接] 我是链接,点我呀:) [题意] 题意 [题解] 因为区间的端点移动一个单位的话,只会涉及到一个元素的增多或减少. 因此可以用莫队算法来解决. 只需要开一个数组(大小1百万),用下标来快速检索 ...

  3. TopCoder[SRM587 DIV 1]:ThreeColorability(900)

    Problem Statement      There is a H times W rectangle divided into unit cells. The rows of cells are ...

  4. NX二次开发-char*转换成CString,多字节转换成Unicode使用方法

    //定义一个结构体记录 struct group { CString text; //定义一个CString std::vector<tag_t> boudaries; std::vect ...

  5. 20-MySQL-Ubuntu-数据表的查询-子查询(九)

    子查询(嵌套查询) select * from students where height=(select max(height) from students);

  6. RocketMQ核心技术精讲与高并发抗压实战

    1:特点 比较吃内存 内存至少1g 默认8g 1:支持集群模型,强调集群无单点,负载均衡以及水平扩展能力2:亿级别的消息堆积能力3:采用零拷贝原理Consumer 消费消息过程,使用了零拷贝 顺序写盘 ...

  7. ECMAScript中所有参数传递的都是值,不可能通过引用传递参数

    今天在看JavaScript高级程序设计(第三版)时,看到了这个问题:ECMAScript中所有参数传递的都是值,不可能通过引用传递参数. 在我的印象中,其他语言比如Java,C++等,传递参数有两种 ...

  8. HTML_案例(注册案例CSS版)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. 8_InlineHook

    1 shellcode低2Gb警告.应使用高2GB 稳定 : 在内核挂钩子: 由于每个进程的低2gb 的数据是不同的:所以 在内核挂钩子 因该把 代码 放在 高 2gb. 方法1(申请): 比如 使用 ...

  10. 详解redis服务

    http://mp.weixin.qq.com/s?__biz=MzIyMDA1MzgyNw==&mid=2651968327&idx=1&sn=6e6cb01d334d7ae ...