您的位置:首页 > 编程语言 > Python开发

使用python爬取教程生成PDF

2018-09-11 00:56 627 查看

工具准备

安装 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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息