Python批量下载某网站贵得要shi文档 并保存为PDF

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

人生苦短我用Python

在这里插入图片描述

基本开发环境💨

  • Python 3.6
  • Pycharm

相关模块的使用💨

import requests
import parsel
import re
import os
import pdfkit

需要使用到一个软件 wkhtmltopdf
这个软件的作用就是把html文件转成PDF

想要把文档内容保存成PDF
首先保存成html文件
然后把html文件转PDF

在这里插入图片描述

💥需求数据来源分析

写爬虫程序

对于数据来源的分析

是比较重要的

因为只有当你知道数据的来源你才能通过代码去实现

请添加图片描述
网站分类有比较多种 也可以选择自己要爬取的。

这个网站如果你只是正常直接去复制文章内容的话

会直接弹出需要费的窗口…

在这里插入图片描述

但是这个网站上面的数据内容又非常好找

因为网站本身仅仅只是静态网页数据

可以直接获取相关的内容。
在这里插入图片描述

通过上述内容如果想要批量下载文章内容

获取每篇文章的url地址即可

想要获取每篇文章的url地址

这就需要去文章的列表页面找寻相关的数据内容了。

在这里插入图片描述


💥整体思路

1. 发送请求对于文章列表url地址发送请求
2. 获取数据获取网页源代码数据内容
3. 解析数据提取文章url地址
4. 发送请求对于文章url地址发送请求
5. 获取数据获取网页源代码数据内容
6. 解析数据提取文章标题以及文章内容
7. 保存数据把获取的数据内容保存成PDF
8. 转成PDF文件

💥代码实现

import requests
import parsel
import re
import os
import pdfkit

html_filename = 'html\\'
if not os.path.exists(html_filename):
    os.mkdir(html_filename)

pdf_filename = 'pdf\\'
if not os.path.exists(pdf_filename):
    os.mkdir(pdf_filename)

html_str = """
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
{article}
</body>
</html>
"""


def change_title(name):
    pattern = re.compile(r"[\/\\\:\*\?\"\<\>\|]")  # '/ \ : * ? " < > |'
    new_title = re.sub(pattern, "_", name)  # 替换为下划线
    return new_title


for page in range(1, 11):
    print(f'正在爬取第{page}页数据内容')
    url = f'https://www.chinawenwang.com/zlist-55-{page}.html'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)
    href = re.findall('<h2><a href="(.*?)" class="juhe-page-left-div-link">', response.text)
    for index in href:
        response_1 = requests.get(url=index, headers=headers)
        selector = parsel.Selector(response_1.text)
        title = selector.css('.content-page-header-div h1::text').get()
        title = change_title(title)
        content = selector.css('.content-page-main-content-div').get()
        article = html_str.format(article=content)
        html_path = html_filename + title + '.html'
        pdf_path = pdf_filename + title + '.pdf'
        try:
            with open(html_path, mode='w', encoding='utf-8') as f:
                f.write(article)

在这里插入图片描述

exe 文件存放的路径

            config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')

把 html 通过 pdfkit 变成 pdf 文件

pdfkit.from_file(html_path, pdf_path, configuration=config)
            print(f'{title}保存成功...')
        except:
            pass

💥实现效果

在这里插入图片描述

PDF文档

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: python