使用python爬取教程生成PDF

工具准备

安装 wkhtmltopdf

https://wkhtmltopdf.org/downloads.html下载稳定版的 wkhtmltopdf 进行安装,安装完成之后把该程序的执行路径加入到系统环境 $PATH 变量中

第三方安装

pip install requests

pip install beautifulsoup4

pip install pdfkit

pip install wkhtmltopdf

实现分析

获取html
首先分析界面URL

第一页:http://www.runoob.com/python/python-exercise-example1.html 第二页:http://www.runoob.com/python/python-exercise-example2.html 第三页:http://www.runoob.com/python/python-exercise-example3.html

...

第一百页:http://www.runoob.com/python/python-exercise-example100.html 由此可以得出URL的规律

url = 'http://www.runoob.com/python/python-exercise-example' + str(i) + '.html' 其中i为1到一百的整数

分析页面的html获取爬取的内容

image

  • 我们要获取到class =article-body,节点下的所有元素
  • 爬取的python示例中编码里面都含有样式,为了按原来的格式展示这里还需要使用一个html模板
代码实现
def get_learn_py_content():
    """
    解析URL,获取需要的html内容
    :return: htmls
    """
    htmls = []

    # 渲染的html模板
    html_template = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="style.css" type="text/css" media="all">
    </head>
    <body>
    {content}
    </body>
    </html>
    """
    for i in range(1,101):
        base_url = 'http://www.runoob.com/python/python-exercise-example' + str(i) + '.html'
        response = requests.get(base_url)
        soup = BeautifulSoup(response.content, 'html.parser')
        # 获取文档内容
        content = soup.find(class_='article-body')
        # 去除图片
        while soup.img:
            soup.img.decompose()
        html = html_template.format(content=content)
        html = html.encode("UTF-8")
        html_name = str(i)+".html"
        with open(html_name, 'wb') as f:
            f.write(html)
        htmls.append(html_name)
    return htmls
将HTML转换成PDF

将Html转换成PDF这里使用的是第三方的包pdfkit,直接将生成的HTML直接传入进来,在传入一个即将要用的PDF的文件名,就完成了

def save_pdf(htmls,name):
    """
    把所有html文件转换成pdf文件
    """
    # views视图中可以加上options进行页面布局调试 
    options = {
        'page-size': 'Letter',
        'encoding': "UTF-8",
        'custom-header': [
            ('Accept-Encoding', 'gzip')
        ]
    }

    pdfkit.from_file(htmls, name, options=options)

转载于:https://my.oschina.net/hellotest/blog/2046470

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值