python自动查找你喜欢的文章 — visit_articles.py文件解析

python自动查找你喜欢的文章 — 解析 — visit_articles.py

代码后面有详细解析,请将文章看完。

import requests  #request是这个项目比较主要的第三方库,用于访问网页
import json  #json用于解析json数据
from printc import Fore, Back, Style  #printc中的三个类,前景色,背景色和样式,其实是colorama里面的
import printc as out  #用于输出彩色字体,c是color、colorful的缩写
import os  #这个模块其实没有什么用,完全没有用到,是作者的失误
from visit import visit  #访问网站,在visit.py中会解析
from urllib.parse import urljoin  #用于将url连接起来,比如https://www.juejin.cn/和/pin连接起来
#引入模块

out.setup_color()  #设置颜色
__=out.get_data()  #将颜色设置保存起来,以后可以使用printcf输出

#json处理
sites=[]  #需要读取的站点
json_sites=open('sites.json', encoding='utf-8')  #打开文件
__json=json_sites.read()  #读取数据
json_sites.close()  #关闭文件
'''详细json数据请见json.md'''

#清除已经访问
visited_sites=open('visited.json', 'w', encoding='utf-8')  #打开文件
visited_sites.write('')  #清空文件
visited_sites.close()  #关闭文件


#判断json是否异常
if __json=='':  #没有json可读
    out.printcf('There\'s no site to read.', __, fg=Fore.RED)
    exit()
try:  #json读取出错
    __json=json.loads(__json)
    out.printcf('站点设置在sites.json,以下是json数据:', __, fg=Fore.GREEN)
    out.printcf(__json, __)
except:
    out.printcf('It seems like there is something wrong with the sites. Please try again.', __, fg=Fore.RED)
    exit()


#开始检查数据是否完整
doing=0
while doing<len(__json):
    __now=__json[doing]  #获取当前项目

    out.printcf('Checking item '+str(doing+1), __, fg=Fore.GREEN)  #输出检查信息

    try:  #json数据是否完好
        if type(__now['url'])!=type(str()) or type(__now['start_from'])!=type(str()):  #数据类型是否完好
            out.printcf('数据出错', __, fg=Fore.RED)
            del __json[doing]
            continue
        out.printcf('链接: '+__now['url'], __)
        out.printcf('开始链接: /'+__now['start_from'], __)
    except:
        out.printcf('数据出错', __, fg=Fore.RED)
        del __json[doing]
        continue

    doing+=1

out.printcf(__json, __)

for site in __json:
    visit(urljoin(site['url'], site['start_from']), __, depth=5)  #一个一个网站爬取

复制代码

为什么要有__来存储颜色设置?

经过计算,直接使用printc输出需要访问color.json来获取颜色设置,会访问硬盘,速度非常慢,要0.0009秒(凡尔赛中)。

但是使用printcf使用存储的颜色设置输出,虽然不能及时更新颜色设置,但是可以一直使用第一次获取的颜色设置输出,时间几乎是0.0秒。

我还没有color.json怎么办?

GitHub上的color.json是我的电脑的配置,由于每个人的电脑和操作系统不同,所以配置本来就是不同的,根本没有必要使用GitHub上的文件,否则会带来很差的体验。

你可以用python运行printc.py来创建颜色设置。
旧版本的printc有可能会导致Windows cmd和Windows powershell无法显示颜色。新版本的printc已经解决了这个问题。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享