---- AI试用 ---域名问题某些图片和js资源无法访问,导致一些代码实例无法运行!(代码里gzui.net换成momen.vip即可)

[Python] 52Pojie指定文章一键生成PDF,方便收藏查看

Python 蚂蚁 655℃ 0评论

https://www.52pojie.cn/thread-1586931-1-1.html

# -*- coding: utf-8 -*-
# @Author: Null119
# @Desc: { 52Pojie文章生成PDF }
# @Date: 2022/02/12 17:55

import os,requests,re,pdfkit,urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def writehtml(path,str):
    f = open(path,'w+',encoding='utf-8')
    f.write(str)
    f.close

def main(savePath,cookie):
    url=input('请输入文章URL:')
    headers={'Cookie':cookie}
    html=requests.get(url.strip(),headers=headers,verify=False).text
    title=re.search(r'id="thread_subject">(.*?)<',html).group(1)
    print('文章:',title)
    td=re.search(r'id="postmessage_\d+">([\S\s]*?)</td>',html).group(1)
    img=re.findall(r'<img aid="\d+".*?\)"',td)
    for i in img:
        exp=re.search('src=.*?file=(".*?").*?\)"',i)
        td=td.replace(exp.group(0),'src='+exp.group(1))
    td='<html><h1><a href="%s">%s</a></h1><br>%s</html>' % (url.strip(),title,td)
    if not os.path.exists(savePath):
        os.makedirs(savePath)
    if (savePath[:-1]!='/' ) and (savePath[:-1]!='\\'):
        savePath=savePath+'/'
    writehtml(savePath+'temp.html',td)
    print('开始生成pdf,请稍候...')
    path_wk = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'  # wkhtmltopdf安装位置
    config = pdfkit.configuration(wkhtmltopdf=path_wk)
    options = {
        'page-size': 'A4',
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        'encoding': "UTF-8",
        'outline': None
    }
    pdfkit.from_file([savePath+'temp.html'], savePath+title+'.pdf',options=options, configuration=config)
    os.remove(savePath+'temp.html') #删除临时html
    print('任务完成!')

if __name__ == '__main__':
    cookie='' #访问保存需要登录浏览权限的文章需要设置cookie
    savePath='E:/吾爱破解/文章收藏/' #保存PDF的目录
    main(savePath,cookie)

注意:代码中使用了pdfkit库来生成PDF,关于这个库要说明一下,PIP安装后直接使用还是会报错,还需要下载安装wkhtmltopdf

下载地址:https://wkhtmltopdf.org/downloads.html
下载安装完成之后在代码中修改相应的path_wk wkhtmltopdf.exe路径就可以了

转载请注明:有爱前端 » [Python] 52Pojie指定文章一键生成PDF,方便收藏查看

喜欢 (2)or分享 (0)