怎么看待CSDN把网上已有的免费资料收录为己有然后需积分下载?
作者:卡卷网发布时间:2024-12-02 18:37浏览数量:105次评论数量:0次
看完上面的回答,我只能说 天下苦Csdn久以 但!
求求你们别骂黄老爷了!!黄老爷这事办的不体面,那咱们就帮他体面体面。
这年头谁没个着急,有时候找到的解决方案他往往就是在csdn某个博主的文章里。看到一半,欸!开通VIP才行!我裤子都脱了你跟我讲这个。拉着脸到处借号,好不容易借到个会员,还要经常输入账号密码。烦得嘞~~
说好了互联网共享精神呢?有没有一种工具直接输入csdn的链接就把文章给down下来?没找到。ok自己写一个! 折腾了好一会 终于把工具写好了!
发出去给朋友们一起用~ 奈何群里很多朋友居然 傻傻分不清,哪些资源是能下载的 哪些资源又是不能下载的。这个把我给愁坏了,又连夜录制了使用说明。以及相关的下载资源介绍,然后上传到了B站 。我把工具链接 和 B站视频 都贴在下面,各位老板可以试着玩一下,我python写得一般,还望道友们轻喷~
在线工具地址:
csdn文章浏览/资源下载B站视频链接:
aa后来B站里会网友问关于源码的分享的问题 我也一起贴在知乎文章这里吧 ~
脚本结构:
csdnflaskhandle.py
import subprocess
import sys
from flask import Flask, request, jsonify
import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from article import CsdnData
from selenium.webdriver.chrome.options import Options
import logging
import configparser
import osutils
config = configparser.ConfigParser()
config.read('config.ini',encoding='utf-8')
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# 创建文件处理器
file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
# 创建流处理器
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
# 将处理器添加到日志记录器
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
app = Flask(__name__)
@app.route('/csdn/article/download', methods=['POST'])
def article_download():
logger.info("当前请求参数是:"+str(request.get_json()))
try:
if request.content_type == 'application/json':
# 处理JSON格式的数据
data = request.get_json()
article_url = data.get('article_url')
download_url = data.get('download_url')
receiver_email = data.get('receiver_email')
format = data.get('format')
# 创建一个Chrome选项对象
chrome_options = Options()
service = Service(config['DEFAULT']['ChromeDriverPath'])
#启动本地Chrome浏览器 不启动无痕方式 (直接避过登录)
chrome_options.add_argument(f'user-data-dir={config['DEFAULT']['WindowsProfilePath']}')
driver = webdriver.Chrome(options=chrome_options,service=service)
directory_path = config['DEFAULT']['DirectoryPath']
try:
csdnDate = CsdnData(driver)
# 根据类型 判断是下载文章还是下载资源
if article_url:
csdnDate.get_article(article_url,format,directory_path,logger)
else:
csdnDate.get_download(download_url,logger)
# 下载完成后发送邮件
if osutils.is_download_completed(directory_path, logger):
latest_file_path = osutils.get_latest_file(directory_path, logger)
#发送邮件
osutils.send_mail(config['DEFAULT']['Email'],config['DEFAULT']['AuthCode'],receiver_email,latest_file_path,logger)
driver.quit()
except RuntimeError as runtimeError:
logger.error(f"下载文章失败,错误内容为:{runtimeError}")
driver.quit()
osutils.send_error_mail(config['DEFAULT']['Email'], config['DEFAULT']['AuthCode'], receiver_email,
str(runtimeError), logger)
return str(runtimeError), 504
return '下载完毕,已发送至邮箱,请查收!', 200
else:
return '提交数据格式不正确',403
except Exception as e:
logger.error(f"下载文章失败,错误内容为:{e}")
# 发送邮件
osutils.send_mail(config['DEFAULT']['Email'], config['DEFAULT']['AuthCode'], receiver_email, "下载异常,请联系管理员解决",
logger)
return "下载异常,请联系管理员解决", 503
finally:
# 杀掉Chrome进程确保下一次请求不受影响
os.system('taskkill /f /im chrome.exe')
if __name__ == '__main__':
# 定义需要安装的模块列表
required_packages = ['flask', 'requests','selenium']
# 检查每个模块是否已安装,未安装的将使用pip安装
for package in required_packages:
try:
# 尝试导入模块
__import__(package)
except ImportError:
# 如果模块未安装,使用pip安装
print(f"安装模块:{package}")
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
app.run(host='0.0.0.0',debug=True,port=5000)
article.py
# csdn 资料处理类
import os
import time
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
class CsdnData:
def __init__(self, driver):
self.driver = driver
#检查链接是否是csdn的文章链接
def check_articleurl(self, url):
if 'csdn.net' in url:
return True
if 't.csdnimg.cn'in url:
return True
return False
def check_downloadurl(self, url):
if 'download.csdn.net' in url:
return True
return False
# 检查是否具备查看的文章权限
def check_permission(self, page_source):
if '订阅专栏 解锁全文' in page_source:
return False
return True
# 检查是否具备下载权限
def check_download(self, page_source):
if "VIP专享下载" in page_source or "立即下载" in page_source:
# 判断下载内容是否超过50MB
file_size_span = self.driver.find_element(By.XPATH,
'/html/body/div[3]/div/div[1]/div/div[2]/div[1]/div[1]/div[2]/div[1]/div[1]/div/div[2]/div[2]/div/span[7]')
# 获取其中文本
file_size = file_size_span.text
# 判断其中是否含有 KB 或者MB 等单位
if 'MB' in file_size:
# 获取其中的数字
file_size = float(file_size.replace('MB', '').strip())
if file_size > 50:
raise RuntimeError("暂不支持下载文件超过50MB,如有需要可以联系管理员手动帮忙下载,微信:")
elif 'KB' in file_size:
pass
else:
# 判断下载内容是否超过50MB
file_size_span = self.driver.find_element(By.XPATH,
'/html/body/div[3]/div/div[1]/div/div[2]/div[1]/div[1]/div[2]/div[1]/div[1]/div/div[2]/div[2]/div/span[6]')
# 获取其中文本
file_size = file_size_span.text
if 'MB' in file_size:
# 获取其中的数字
file_size = float(file_size.replace('MB', '').strip())
if file_size > 50:
raise RuntimeError("暂不支持下载文件超过50MB,如有需要可以联系管理员手动帮忙下载,微信:")
return True
def try_download_file(self,logger):
# 点击立即下载按钮
try:
download_button = self.driver.find_element(By.XPATH,
'/html/body/div[3]/div/div[1]/div/div[3]/div[1]/div[1]/div[2]/div[1]/div[3]/div[1]/button/span/span')
download_button.click()
except Exception as e:
logger.info("点击下载按钮出错,正在重试")
download_button = self.driver.find_element(By.XPATH,
"/html/body/div[3]/div/div[1]/div/div[2]/div[1]/div[1]/div[2]/div[1]/div[3]/div[1]/button/span/span")
download_button.click()
logger.info("点击下载按钮")
time.sleep(2)
# 在弹窗页面中找到VIP专享下载按钮
try:
vip_download_button = self.driver.find_element(By.XPATH,
'/html/body/div[3]/div/div[1]/div/div[4]/div/div[3]/div/div/button')
vip_download_button.click()
except Exception as e:
try:
logger.info("点击VIP专享下载按钮出错,正在重试")
vip_download_button = self.driver.find_element(By.XPATH,
"/html/body/div[3]/div/div[1]/div/div[3]/div/div[3]/div/div/button")
vip_download_button.click()
except Exception as e:
logger.error(f"点击VIP专享下载按钮出错,错误内容为:{e}")
self.driver.quit()
os.system('taskkill /f /im chrome.exe')
raise RuntimeError("Csdn账号今天已达到下载上限啦~ 该功能明天再开放! (文章浏览功能正常使用中)")
logger.info("点击VIP专享下载按钮,开始下载文件...")
time.sleep(3)
def get_article(self, url,format,directory_path,logger):
if not self.check_articleurl(url):
raise RuntimeError("链接不是csdn的文章")
self.driver.get(url)
#获取请求后的页面源码
page_source = self.driver.page_source
#检查是否具备查看的文章权限
check_permission = self.check_permission(page_source)
if not check_permission:
raise RuntimeError("专栏文章,没有查看文章的权限")
ActionChains(self.driver).send_keys('aa').perform()
time.sleep(3)
ActionChains(self.driver).send_keys('sr').perform()
time.sleep(2)
if format == 'screenshot':
# 获取目录中的所有文件和文件夹
files_and_folders = os.listdir(directory_path)
# 当前文件中的个数
file_num = len(files_and_folders)
ActionChains(self.driver).send_keys('pg').perform()
# 由于导出图片功能不一定能够成功,所以需要计数 如果检查超过30秒仍然没有导出图片,那么就认为导出失败
start_time = time.time()
while True:
files_and_folders = os.listdir(directory_path)
if len(files_and_folders) > file_num:
break
if time.time() - start_time > 30:
logger.info(f"导出图片失败")
raise RuntimeError("导出图片失败")
time.sleep(1)
logger.info(f"当前图片正在下载中...")
else:
ActionChains(self.driver).send_keys('oh').perform()
time.sleep(3)
def get_download(self,url,logger):
# 检查url链接是否有问题
if not self.check_downloadurl(url):
raise RuntimeError("链接不是csdn的下载链接")
#获取请求后的页面源码
self.driver.get(url)
# 获取请求后的页面源码
page_source = self.driver.page_source
# 检查页面是否具备下载的权限
self.check_download(page_source)
# 尝试下载文件
self.try_download_file(logger)
osutils.py
import os
import time
from csdnreptiles.qqemail import QQMailer
# 检查下载是否完成
def is_download_completed(download_dir,logger):
# 循环检查下载文件夹中是否还有临时文件
while any([filename.endswith(".crdownload") for filename in os.listdir(download_dir)]):
# 找到存在的crdownload文件
for filename in os.listdir(download_dir):
if filename.endswith(".crdownload"):
logger.info(f"存在crdownload文件: {filename} 下载中...")
time.sleep(1) # 等待1秒再次检查
return True
# 获取目录中最新的文件
def get_latest_file(directory_path,logger):
# 获取目录中的所有文件和文件夹
files_and_folders = os.listdir(directory_path)
# 过滤出文件列表
files = [f for f in files_and_folders if os.path.isfile(os.path.join(directory_path, f))]
# 初始化最新文件的时间戳和路径
latest_timestamp = 0
latest_file_path = None
# 遍历文件列表,找到最新生成的文件
for file in files:
file_path = os.path.join(directory_path, file)
file_timestamp = os.path.getmtime(file_path) # 获取文件最后修改时间的时间戳
if file_timestamp > latest_timestamp:
latest_timestamp = file_timestamp
latest_file_path = file_path
# 打印最新生成的文件路径
logger.info(f"最新生成的文件路径: {latest_file_path}")
return latest_file_path
# 发送邮件
def send_mail(sender,auth_code,receiver_email,latest_file_path,logger):
mailer = QQMailer(sender, auth_code)
mailer.send_mail(
receiver_email=receiver_email,
subject="csdn资源助手",
body="csdn文章资源自助服务内容,请在附件中查看您的文章内容",
attachment_path=latest_file_path
)
logger.info("邮件发送成功!")
def send_error_mail(sender,auth_code,receiver_email,notes,logger):
mailer = QQMailer(sender, auth_code)
mailer.send_mail(
receiver_email=receiver_email,
subject="csdn资源助手",
body="csdn文章资源自助服务内容,下载失败,失败原因:"+notes,
)
logger.info("已邮件通知下载失败!")
qqemail.py
import os
import time
from csdnreptiles.qqemail import QQMailer
# 检查下载是否完成
def is_download_completed(download_dir,logger):
# 循环检查下载文件夹中是否还有临时文件
while any([filename.endswith(".crdownload") for filename in os.listdir(download_dir)]):
# 找到存在的crdownload文件
for filename in os.listdir(download_dir):
if filename.endswith(".crdownload"):
logger.info(f"存在crdownload文件: {filename} 下载中...")
time.sleep(1) # 等待1秒再次检查
return True
# 获取目录中最新的文件
def get_latest_file(directory_path,logger):
# 获取目录中的所有文件和文件夹
files_and_folders = os.listdir(directory_path)
# 过滤出文件列表
files = [f for f in files_and_folders if os.path.isfile(os.path.join(directory_path, f))]
# 初始化最新文件的时间戳和路径
latest_timestamp = 0
latest_file_path = None
# 遍历文件列表,找到最新生成的文件
for file in files:
file_path = os.path.join(directory_path, file)
file_timestamp = os.path.getmtime(file_path) # 获取文件最后修改时间的时间戳
if file_timestamp > latest_timestamp:
latest_timestamp = file_timestamp
latest_file_path = file_path
# 打印最新生成的文件路径
logger.info(f"最新生成的文件路径: {latest_file_path}")
return latest_file_path
# 发送邮件
def send_mail(sender,auth_code,receiver_email,latest_file_path,logger):
mailer = QQMailer(sender, auth_code)
mailer.send_mail(
receiver_email=receiver_email,
subject="csdn资源助手",
body="csdn文章资源自助服务内容,请在附件中查看您的文章内容",
attachment_path=latest_file_path
)
logger.info("邮件发送成功!")
def send_error_mail(sender,auth_code,receiver_email,notes,logger):
mailer = QQMailer(sender, auth_code)
mailer.send_mail(
receiver_email=receiver_email,
subject="csdn资源助手",
body="csdn文章资源自助服务内容,下载失败,失败原因:"+notes,
)
logger.info("已邮件通知下载失败!")
config.ini 配置
[DEFAULT]
# Chrome浏览器驱动路径
ChromeDriverPath =
# Chrome浏览器安装地址
windowsProfilePath =
DirectoryPath =
SMTPServer = smtp.qq.com
# 发送人的QQ邮箱
Email =
# 发送人QQ邮箱授权码
AuthCode =
免责声明:本文由卡卷网编辑并发布,但不代表本站的观点和立场,只提供分享给大家。
- 上一篇:在网络安全领域,比较牛的中国黑客有哪些?
- 下一篇:天涯里面最神的神贴是什么?
相关推荐

你 发表评论:
欢迎