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 ...
随机推荐
- 29. StringBuilder
1.字符串变量.StringBuffer.StringBulid的区别: 字符串是一个常量,不能被修改 字符串一旦被修改,那么会再创建一个对象,浪费空间 而 ...
- [Nowcoder] 保护
题意:... 思路: \(LCA\)乱搞+启发式合并(堆) #include <bits/stdc++.h> using namespace std; const int maxn = 2 ...
- 7.RabbitMQ RFC同步调用
RabbitMQ RFC同步调用是使用了两个异步调用完成的,生产者调用消费者的同时,自己也作为消费者等待某一队列的返回消息,消费者接受到生产者的消息同时,也作为消息发送者发送一消息给生产者.参考下图: ...
- 大数据-KNN算法
KNN是通过测量不同特征值之间的距离进行分类.它的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别,其中K通常是不大于20的整数 ...
- Java-Class-C:com.alibaba.fastjosn.JSON
ylbtech-Java-Class-C:com.alibaba.fastjosn.JSON 1.返回顶部 1.1.import com.alibaba.fastjson.JSON;import co ...
- bagging和boosting以及rand-forest
bagging: 让该学习算法训练多轮,每轮的训练集由从初始的训练集中随机取出的n个训练样本组成,某个初始训练样本在某轮训练集中可以出现多次或根本不出现,训练之后可得到一个预测函数序列h_1,⋯ ⋯h ...
- 如果一个文件块有130M,请问有多少个mapper
如果一个文件块有130M,请问有多少个mapper 130M的文件将被分成2个mapper. 原因:根据FileInputFormat类 有一个成员变量 private static final do ...
- USACO2012 Broken necklace /// DP oj10103
题目大意: 项链最长的纯色连续段,“w”即white白色珠子,可任意涂为红或蓝,“r” “b”即红 蓝. Input Line 1: N, the number of beads Line 2: ...
- Js_案例(电灯)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- spark安装及配置
windows下spark的安装与配置教程 Windows下安装spark windows下搭建spark环境出现ChangeFileModeByMask error (3): ??????????? ...