cosmic_download-AsyncPool待修正
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/16 10:02 AM
# @Author : cxa
# @File : cosmic.py
# @Software: PyCharm
# encoding: utf-8
import os
import aiohttp
import hashlib
import base64
from cryptography.fernet import Fernet
import aiofiles
import multiprocessing
import async_timeout
from lxml import html
import asyncio
from aiologger import Logger
import asyncpool
workers = multiprocessing.cpu_count() * 2 + 1
# 开始索引数
start_num = 227002
# 结束索引数
# end_num = 227006
end_num = 250606
key = "X0JxSkg4NFVBQVBPODlUM0VzT1liNnloeWtLcndkSldRT2xURzQ4MEM5RT0="
page_num_xpath = "//p[@class='selectpage']/select[@id='page_number']/option[last()]/@file"
page_id_xpath = "//img[@id='thumbnail']/@src"
def aes_cbc_decrypt(message):
decrypted_text = Fernet(base64.b64decode(key).decode("utf8")).decrypt(bytes("{}".format(message), encoding="utf8"))
return decrypted_text.decode("utf8")
# 漫画题目
cosmic_name = "//head//title/text()"
# 漫画id
cosmic_id = "//img[@id='curPic']/@src"
main_url = aes_cbc_decrypt(
"gAAAAABbNdhqCnxkaJwZ2VL7HUXne_IOic-NsHtE30W-J68oecVmgm0dzO_lLXgTlI7a5_NbUWlkGm7FqLwY81XIBddNWbac4rCgBA9NFAECsNISkhTvdRl4uDSaS6bHY8sbcJJwO13Z")
cosmic_url_gen = (main_url.format(i) for i in range(start_num, end_num + 1))
full_url = aes_cbc_decrypt(
"gAAAAABbNdk5FLeX55hOiDAXxgCwwYmGrokYvU3Nd1AOYuOE7OdIEcBdAmSG_Q3kOltealBKMOgUBKDuPUJtzFFPwqoxL-FUip"
"VNQU-JmBW_K5qxgzTQ3IOla_F61Rscy0fJOaN-mEXKPqrakctyDRN7OVm1LARTMhylQELLuBnJgIT4WXilchg=") # 漫画的总id,序号的id和格式使用(jpg)
sema = asyncio.Semaphore(5)
sem_img = asyncio.Semaphore(50)
async def logging():
logger = Logger.with_default_handlers(name='cosmic_download')
return logger
async def get_buff(url, c_name, session, log):
with async_timeout.timeout(60):
async with session.get(url) as r:
buff = await r.read()
if not len(buff):
url = url.replace(".jpg", ".png")
async with session.get(url) as r2:
buff = await r2.read()
await log.info(f"NOW_URL:, {url}")
await get_img(url, buff, c_name, log)
async def run_img(url, c_name, session, log):
async with sem_img:
await get_buff(url, c_name, session, log)
async def get_img(url, buff, c_name, log):
# 题目那层目录
filepath = os.path.join(os.getcwd(), "comics_images", c_name)
# 如果标题太长就转md5,然后单独启动一个text写入内容为标题
md5name = hashlib.md5(c_name.encode("utf-8")).hexdigest()
filepath2 = os.path.join(os.getcwd(), "comics_images", md5name)
id = url.split('/')[-1]
image_id = os.path.join(filepath, id)
image_id2 = os.path.join(filepath2, md5name)
# 题目层目录是否存在
if not os.path.exists(filepath) and not os.path.exists(filepath2):
try:
os.makedirs(filepath)
except:
os.makedirs(filepath2)
image_id = image_id2
fs = await aiofiles.open(os.path.join(filepath2, "title.txt"), 'w')
await fs.write(c_name)
# 文件是否存在
if not os.path.exists(image_id) and not os.path.exists(image_id2):
await log.info(f"SAVE_PATH:{image_id}")
async with aiofiles.open(image_id, 'wb') as f:
await f.write(buff)
async def fetch(url, session, log, retry_index=0):
try:
with async_timeout.timeout(30):
async with session.get(url, verify_ssl=False) as req:
res_status = req.status
if res_status == 200:
text = await req.text()
root = html.fromstring(text)
name = root.xpath(cosmic_name)[0]
jpg_id = root.xpath(page_id_xpath)[0].split('/')[-2]
max_page = root.xpath(page_num_xpath)[0].split('.')[0]
full_url_gen = (full_url.format(jpg_id, i, "jpg") for i in range(1, int(max_page) + 1))
tasks = [asyncio.ensure_future(run_img(img_url, name, session, log)) for img_url in full_url_gen]
await asyncio.gather(*tasks)
except Exception as e:
text = None
if not text:
await log.error(f'Retry times: {retry_index + 1}')
retry_index += 1
return await fetch(url, session, log, retry_index)
async def bound_fetch(url, session, log):
async with sema:
await fetch(url, session, log)
async def run(data):
log = await logging()
result_queue = asyncio.Queue()
await log.info("Start Spider")
async with asyncpool.AsyncPool(loop, num_workers=10, name="cosmic",
logger=log, worker_co=bound_fetch) as pool:
async with aiohttp.connector.TCPConnector(limit=100, force_close=True, enable_cleanup_closed=True) as tc:
async with aiohttp.ClientSession(connector=tc) as session:
for url in data:
await pool.push(url, session, log)
await result_queue.put(None)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(run(cosmic_url_gen))
loop.close()
项目地址:https://github.com/muzico425/cosmic_download
cosmic_download-AsyncPool待修正的更多相关文章
- [修正] Firemonkey 中英文混排折行问题(移动平台)
问题:FMX 在移动平台的文字显示并非由该平台的原生 API 来显示,而是由 FMX.TextLayout.GPU 来处理,也许是官方没留意到中文字符的问题,造成在中英文混排折行时,有些问题. 适用: ...
- [修正] Firemonkey Android 显示 Emoji (颜文字)
问题:在 Android 平台下,显示 Emoji 文字,无法显示彩色(皆为黑色),例如 Edit 控件,即使将 Edit.ControlType = Platform 设为平台原生控件,还是没用(真 ...
- 2016 正确 sublime安装PHPcs PHPcodesniffer代码规范提示插件,修正网上部分不详细描述
对你有助请点赞,请顶,不好请踩------送人玫瑰,手留余香!-------------------14:37 2016/3/212016 正确 sublime安装PHPcs PHPcodesniff ...
- Mint Linux 安装 DotnetCore 遭遇无法修正错误,因为您要求某些软件包保持现状,就是它们破坏了软件包间的依赖关系
evlon@evlon-ThinkPad-T530 ~ $ apt install dotnet-dev-1.0.0-preview2-003121 正在读取软件包列表... 完成 正在分析软件包的依 ...
- 修正IE6不支持position:fixed的bug(转)
众所周知IE6不支持position:fixed,这个bug与IE6的双倍margin和不支持PNG透明等bug一样臭名昭著.前些天我做自己的博客模板的时候,遇到了这个问题.当时就简单的无视了IE6— ...
- [修正] 移动平台曲线不平滑的问题(如:TRectangle, TPath...等)
问题:从 XE4 以来,Firemonkey 曲线绘图在移动平台不平滑的问题一直令人诟病,提交到官方的 QC 也是族繁不及备载,官方似乎有意的避开这个问题,迟迟没有修正. 适用版本:XE4 ~ Ber ...
- [修正] Firemonkey TSelection 控件等比缩放时,左下角拉动问题
说明:TSelection 控件,当在属性 Proportional = True 为等比缩放时,拉动左下角,右上角会跟着移动. 适用:Berlin 10.1.1 (或之前版本) Firemonkey ...
- [修正] Berlin Firemonkey Windows 控件左方显示虚线问题
说明:在 Wndows 显示时,有时控件左方会显示一条虚线 适用:Berlin Firemonkey 修正方法: 请将源码 FMX.Platform.Win.pas 复制到自己的工程目录里,再进行修改 ...
- 查看数据库表的数据量和SIZE大小的脚本修正
在使用桦仔的分享一个SQLSERVER脚本(计算数据库中各个表的数据量和每行记录所占用空间)的脚本时,遇到下面一些错误 这个是因为这些表的Schema是Maint,而不是默认的dbo,造成下面这段SQ ...
随机推荐
- Ubuntu vim下 实现函数跳转功能
安装sudo apt-get install exuberant-ctags 在每次使用时,需要初始化tags,只有这样才能使用跳转功能 初始化: 进入项目的顶级目录.输入以下命令. ...
- powershell 中常用cmd,unix命令(get-alias)
powershell 中常用cmd,unix命令(get-alias) Get-Content Alias cat -> Get-Content Alias gc -> Get-Conte ...
- VScode 1.13 gocode提示dial tcp 216.239.37.1:443: connectex: A connection attempt failed because the connected..
在将VScode升级至 1.13后让升级gocode,在升级时报出如下错误 D:\go_work\src>go get -u -v github.com/mdempsky/gocode gith ...
- 如何用java语言实现C#中的ref关键字(按引用传递参数)的效果
https://www.cnblogs.com/nnngu/p/8300164.html
- HTTP访问控制(CORS)
当一个资源从与该资源本身所在的服务器不同的域或端口请求一个资源时,资源会发起一个跨域 HTTP 请求. 比如,站点 http://domain-a.com 的某 HTML 页面通过 <img ...
- XXE攻防技术
http://bobao.360.cn/learning/detail/3841.html http://www.freebuf.com/articles/web/97833.html http:// ...
- 求f(n)=[n/1]+[n/2]+---+[n/n]的值 简单杂题
这种小题首先根据 n/1+n/2+n/3+--+n/n=nlogn+欧拉常数r 可以知道 1e12的范围也不会爆longlong,不需要写高精度(到现在都不会写) 再根据数据范围可知O(n)级别的暴力 ...
- 【bzoj 3173】[Tjoi2013]最长上升子序列
Description 给定一个序列,初始为空.现在我们将1到N的数字插入到序列中,每次将一个数字插入到一个特定的位置.每插入一个数字,我们都想知道此时最长上升子序列长度是多少? Input 第一行一 ...
- webstorm破解版
链接:https://www.cnblogs.com/LUA123/p/8452501.html#undefined
- 第25月第4天 Blog-API-with-Django-Rest-Framework项目记录01
#------------------------------ 1. djangochinaorg项目 https://github.com/DjangoChinaOrg/Django-China-A ...