使用python爬取教程生成PDF
2018-09-11 00:56
726 查看
工具准备
安装 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获取爬取的内容
我们要获取到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)
相关文章推荐
- php使用TCPDF生成PDF文件教程
- 利用Python的Django框架生成PDF文件的教程
- python之使用 wkhtmltopdf 和 pdfkit 批量加载html生成pdf,适用于博客备份和官网文档打包
- 使用PDFLib生成PDF文档教程
- 在Python中使用CasperJS获取JS渲染生成的HTML内容的教程
- phonegap教程使用jspdf库在应用中生成pdf文件(pdf生成方法)
- Python使用plotly生成本地文件教程
- Python学习之使用Python生成PDF报告
- 使用PDFLib生成PDF文档教程
- TPYBoard MicroPython 固件开发教程使用mpy-cross工具生成mpy文件
- 使用Python生成PDF格式的文档
- 利用Python的Django框架生成PDF文件的教程
- 使用Rose教程(PDF)
- 使用 iText动态生成PDF文档
- 使用PDFLib生成PDF文档,C代码实例--使用特色
- 使用PDFLib生成PDF文档,C代码实例--画图形
- Itext 生成 pdf文件使用方法:
- 使用java生成pdf文档
- 使用ireport做pdf报表,生成的pdf一直都是文件损坏,无法打开,哪位大侠指点一下
- C#分析数据库结构,使用XSL模板自动生成代码 - 清清月儿 .NET万花筒 Asp.net技术 Asp.net教程 Asp.net源码 Asp.net基础 Asp.net控件 Asp.net入门 - CSDNBlog