# coding:utf-8

import re
import ssl
import csv
import json
import time
import random
import asyncio
import aiohttp
import requests
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()
market_cap_all = 0
currency_rate = 0 # 线上内网
socks5_address_prod = [
'socks5://10.1.100.253:1235',
'socks5://10.1.100.51:1235',
'socks5://10.1.100.70:1235',
'socks5://10.1.100.205:1235',
'socks5://10.1.100.73:1235'
] # 办公网
socks5_address_dev = [
'socks5://18.208.81.123:1235',
'socks5://34.197.217.25:1235',
'socks5://52.20.255.43:1235',
'socks5://34.237.163.87:1235',
'socks5://18.208.81.123:1235',
'socks5://52.0.114.155:1235'
] DEPLOY_MODE = "dev" 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()
if DEPLOY_MODE == "dev":
socks = None
elif DEPLOY_MODE == "Prod":
socks = random.choice(socks5_address_prod)
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(cid, url, response):
coin_info = {}
coin_value = {} coin_info['url'] = url
coin_info['cid'] = cid
coin_info['time'] = int(time.time()) tree = etree.HTML(response) try:
price_usd = tree.xpath(
'//div[@class="priceInfo"]/div[@class="sub"]/span[1]/text()'
)[0].strip().replace('$', '')
if '?' not in price_usd:
coin_value['price'] = float(price_usd)
except BaseException:
pass try:
updown = tree.xpath(
'//div[@class="priceInfo"]/div[@class="sub smallfont"]/span[1]/text()'
)[0].strip().replace('%', '')
coin_value['updown'] = float(updown)
except BaseException:
pass try:
volume_24h_rmb = tree.xpath(
'//div[@class="info"]/div[@class="charCell"][2]/div[2]/span/text()'
)[0].strip().replace('¥', '').replace(',', '')
coin_value['volume_24h'] = int(
float(volume_24h_rmb) / Common.currency_rate)
except BaseException:
pass try:
circulating_supply = tree.xpath(
'//div[@class="info"]//div[@class="charCell"][1]/div[@class="val"]/text()'
)[0].strip().replace(',', '')
if '?' not in circulating_supply:
circulating_supply = re.match(
r'^(\d+)(\w+)$', circulating_supply).group(1)
coin_value['circulating_supply'] = int(circulating_supply)
except BaseException:
pass try:
if coin_value['price'] and coin_value['circulating_supply']:
market_cap = coin_value['price'] * coin_value['circulating_supply']
coin_value['market_cap'] = market_cap
except BaseException:
pass try:
if coin_value['market_cap']:
global_share = coin_value['market_cap'] / Common.market_cap_all
if global_share < 0.001:
coin_value['global_share'] = '<0.1%'
else:
coin_value['global_share'] = str(
(global_share * 100).__round__(2)) + '%'
except BaseException:
pass try:
circulation_rate = tree.xpath(
'//div[@class="info"]//div[@class="charbox"][1]/div[@class="val"]/text()'
)[0].strip()
if '?' not in circulation_rate:
coin_value['circulation_rate'] = circulation_rate
except BaseException:
pass try:
turnover_rate = tree.xpath(
'//div[@class="info"]//div[@class="charbox"][1]/div[@class="val"]/text()'
)[1].strip()
if '?' not in turnover_rate:
coin_value['turnover_rate'] = turnover_rate
except BaseException:
pass try:
issue_time = tree.xpath(
'//div[@class="infoList"]/div[1]/div[1]/span[2]/text()'
)[0].strip()
if issue_time != '-':
coin_value['issue_time'] = issue_time
except BaseException:
pass try:
exchange_num = tree.xpath(
'//div[@class="infoList"]/div[3]/div[1]/span[2]/text()'
)[0].strip().replace('家', '')
coin_value['exchange_num'] = int(exchange_num)
except BaseException:
pass try:
total_circulation = tree.xpath(
'//div[@class="infoList"]/div[2]/div[2]/span[2]/text()'
)[0].strip().replace(',', '')
coin_value['total_circulation'] = int(total_circulation)
except BaseException:
pass coin_info['value'] = coin_value
return coin_info async def down_and_parse_task(queue):
while True:
try:
cid, url = queue.get_nowait()[:2]
except BaseException:
return
for retry_cnt in range(3):
try:
html, status = await download(url)
if status != 200:
html, status = await download(url)
if '访问控制拒绝了你的请求' in html:
html, status = await download(url)
html_parse_result = await parse_html(cid, url, html)
print(html_parse_result)
await Common.result_queue.put(html_parse_result)
break
except BaseException:
await asyncio.sleep(0.2)
continue async def push(data):
url = 'http://127.0.0.1:8000/aaa'
error = None
for retry_cnt in range(3):
try:
async with aiohttp.ClientSession() as session:
async with session.post(
url,
data=json.dumps(data)
) as response:
pass
response.raise_for_status()
except Exception as e:
await asyncio.sleep(0.2)
print(e) async def speed_monitor():
while Common.task_queue.qsize() != 0:
old_queue_len = Common.task_queue.qsize()
await asyncio.sleep(5)
new_queue_count = Common.task_queue.qsize()
print('=================')
print('speed = ', (old_queue_len - new_queue_count) / 5) async def monitor_finish():
while len(asyncio.Task.all_tasks()) > 3:
await asyncio.sleep(1)
await asyncio.sleep(5)
raise SystemExit() async def push_results():
temp_q = []
while True:
try:
await asyncio.sleep(3)
for _ in range(Common.result_queue.qsize()):
temp_q.append(await Common.result_queue.get())
if len(temp_q) > 0:
await push(temp_q)
temp_q.clear()
except BaseException:
import traceback
print(traceback.format_exc()) async def get_marketcap():
url = 'https://dncapi.feixiaohao.com/api/home/global?webp=0'
response = requests.get(url)
response_json = json.loads(response.text)
marketcap = response_json['data']['marketcapvol']
Common.market_cap_all = int(marketcap) async def get_currency_rate():
url_rate = 'https://dncapi.feixiaohao.com/api/coin/web-rate/'
response = requests.get(url_rate)
currency_rate = json.loads(response.text)[11]['cny']
Common.currency_rate = currency_rate # 300秒抓取时间上限
async def time_limit():
await asyncio.sleep(280)
raise SystemExit() async def main():
# loop = asyncio.get_event_loop()
csv_reader = csv.reader(
open(
'feixiaohao_mapping_data.csv',
encoding='utf-8'))
for row in csv_reader:
try:
if row[1].startswith('https'):
await Common.task_queue.put(row)
except BaseException:
pass
print(Common.task_queue) await get_marketcap()
print('总市值', Common.market_cap_all) await get_currency_rate()
print('汇率', Common.currency_rate) for _ in range(10):
loop.create_task(down_and_parse_task(Common.task_queue))
loop.create_task(monitor_finish())
loop.create_task(speed_monitor())
loop.create_task(push_results())
loop.create_task(time_limit()) if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()

20.multi_case07的更多相关文章

  1. CSharpGL(20)用unProject和Project实现鼠标拖拽图元

    CSharpGL(20)用unProject和Project实现鼠标拖拽图元 效果图 例如,你可以把Big Dipper这个模型拽成下面这个样子. 配合旋转,还可以继续拖拽成这样. 当然,能拖拽的不只 ...

  2. ABP(现代ASP.NET样板开发框架)系列之20、ABP展现层——动态生成WebApi

    点这里进入ABP系列文章总目录 ABP(现代ASP.NET样板开发框架)系列之20.ABP展现层——动态生成WebApi ABP是“ASP.NET Boilerplate Project (ASP.N ...

  3. 帮我做个APP,给你20万,做不做?

    一.为什么要写这篇文章 前段时间,有个辞职 创业的同事(做法务的)  问我 开发一个 新闻类的APP要多少钱,产品.UI.接口.后台管理页  他们啥都没有,想全部外包. 我 并没有在外包公司做过,也没 ...

  4. ASP.NET MVC5+EF6+EasyUI 后台管理系统(20)-权限管理系统-根据权限获取菜单

    系列目录 不知不觉到20讲,真是漫长的日子,可惜最近工作挺忙,要不可以有更多的时间来更新,多谢大家的一路支持.如果你觉得好,记得帮我点击推荐^-^ 我们在之前已经插入一些真实数据,其中包含了一个用户和 ...

  5. LINQ to SQL语句(20)之存储过程

    在我们编写程序中,往往需要一些存储过程,在LINQ to SQL中怎么使用呢?也许比原来的更简单些.下面我们以NORTHWND.MDF数据库中自带的几个存储过程来理解一下. 1.标量返回 在数据库中, ...

  6. C#开发微信门户及应用(20)-微信企业号的菜单管理

    前面几篇陆续介绍了很多微信企业号的相关操作,企业号和公众号一样都可以自定义菜单,因此他们也可以通过API进行菜单的创建.获取列表.删除的操作,因此本篇继续探讨这个主体,介绍企业号的菜单管理操作. 菜单 ...

  7. 20个非常有用的Java程序片段

    下面是20个非常有用的Java程序片段,希望能对你有用. 1. 字符串有整型的相互转换 String a = String.valueOf(2); //integer to numeric strin ...

  8. 20个不可思议的 WebGL 示例和演示

    WebGL 是一项在网页浏览器呈现3D画面的技术,有别于过去需要安装浏览器插件,通过 WebGL 的技术,只需要编写网页代码即可实现3D图像的展示.WebGL 可以为 Canvas 提供硬件3D加速渲 ...

  9. 20款 JavaScript 开发框架推荐给前端开发者

    下面,我们给大家提供了一个用于 HTML5 开发的各种用途的 JavaScript 库列表.这些框架能够给前端开发人员提供更好的功能实现的解决方案.如果你有收藏优秀的框架,也可以在后面的评论中分享给我 ...

随机推荐

  1. 关于移动端使用swiper做图片文字轮播的思考

    最近做移动端网页的时候,需要在首页添加一个公告的模块,用来轮播公告消息标题并且能链接到相应的详情页面,最开始用的是swiper插件,在安卓上测试完全没有问题,但是在苹果机上就没有那么灵敏了,来回切换首 ...

  2. 微信小程序--跳转页面常用的两种方法

    一.bindtap="onProductsItemTap"绑定点击跳转事件 在.wxml文件中绑定 在.js文件中实现绑定事件函数 二.navigator标签配合URL跳转法 在w ...

  3. map、filter、forEach、reduce数组方法的封装

    1.map方法的封装 ​Array.prototype.mapAlley = function(callback){    //获取调用mapAlley这个方法的数组    let arr = thi ...

  4. Netty环境安装配置

    本章中介绍的Netty开发环境的安装及配置; 这个一系列教程示例的Netty最低要求只有两个:最新版本的Netty 4.x和JDK 1.6及更高版本. 最新版本的Netty在项目下载页面中可找到:ht ...

  5. css中的zoom的作用

    1.检查页面的标签是否闭合不要小看这条,也许折腾了你两天都没有解决的 CSS BUG 问题, 却仅仅源于这里.毕竟页面的模板一般都是由开发来嵌套的,而 他们很容易犯此类问题.快捷提示:可以用 Drea ...

  6. 金三银四铜五铁六,Offer收到手软!

    作者:鲁班大师 来源:cnblogs.com/zhuoqingsen/p/interview.html 文中的鲁班简称LB 据说,金三银四,截止今天为止面试黄金时间已经过去十之八九,而LB恰逢是这批面 ...

  7. python学习6—数据类型之集合与字符串格式化

    python学习6—数据类型之集合与字符串格式化 1. 使用id()可以查看一个变量的内存地址: name = 'alex' id(name) 2. 进制转换 十进制转换为二进制等: a = 10 # ...

  8. HDU 3966 /// 树链剖分+树状数组

    题意: http://acm.hdu.edu.cn/showproblem.php?pid=3966 给一棵树,并给定各个点权的值,然后有3种操作: I x y z : 把x到y的路径上的所有点权值加 ...

  9. 将数据写到kafka的topic

    package test05 import java.util.Propertiesimport org.apache.kafka.clients.producer.{KafkaProducer, P ...

  10. mysql sql的分类、运算符、常用的数据类型

    SQL (结构化查询语言)的分类 DML(数据操作语言),关键字 insert,update,delete, DCL(数据控制语言),控制权限,grand,revoke 授权,回收 DDL(数据定义语 ...