Python爬取廖雪峰教程存为PDF

简介:

首先感谢廖老师给我们大家提供的那么好的教程,相信大部分童鞋都看过廖老师的python教程,我也是从这个教程入了门。后来又开始接着学JavaScript,不过每次都要用浏览器上网浏览太麻烦,所以就用爬虫爬下来保存为PDF格式。不过缺点就是没有目录废话不多说上代码。


# coding=utf-8
import os
import time
import re
import requests
import pdfkit
from bs4 import BeautifulSoup
from PyPDF2 import PdfFileMerger,PdfFileReader, PdfFileWriter
import sys #test12 html_template = """ <!DOCTYPE html>
<body>
<html lang="en"> <head> <meta charset="UTF-8"> </head> {content}
path_wk = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' #安装位置
</body> </html> """ config = pdfkit.configuration(wkhtmltopdf = path_wk)
def parse_url_to_html(url, name):
#---------------------------------------------------------------------- """ 解析URL,返回HTML内容 :param url:解析的url :param name: 保存的html文件名
body = soup.find_all(class_="x-wiki-content")[0]
:return: html """ try: response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') # 正文 # 标题
center_tag.insert(1, title_tag)
title = soup.find('h4').get_text() # 标题加入到正文的最前面,居中显示 center_tag = soup.new_tag("center") title_tag = soup.new_tag('h1') title_tag.string = title
if not m.group(3).startswith("http"):
body.insert(1, center_tag) html = str(body) # body中的img标签的src相对路径的改成绝对路径 pattern = "(<img .*?src=\")(.*?)(\")" def func(m):
html = html_template.format(content=html)
rtn = m.group(1) + "http://www.liaoxuefeng.com" + m.group(2) + m.group(3) return rtn else: return m.group(1)+m.group(2)+m.group(3) html = re.compile(pattern).sub(func, html)
def get_url_list():
html = html.encode("utf-8") with open(name, 'wb') as f: f.write(html) return name except Exception as e: print ("解析错误!") #---------------------------------------------------------------------- """
menu_tag = soup.find_all(class_="uk-nav uk-nav-side")[1]
获取所有URL目录列表 :return: """ response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000") soup = BeautifulSoup(response.content, "html.parser") urls = []
def save_pdf(htmls, file_name):
for li in menu_tag.find_all("div"): url = "http://www.liaoxuefeng.com" + li.a.get('href') urls.append(url) return urls #---------------------------------------------------------------------- """ 把所有html文件保存到pdf文件
'custom-header': [
:param htmls: html文件列表 :param file_name: pdf文件名 :return: """ options = { 'page-size': 'Letter', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', 'encoding': "UTF-8",
#----------------------------------------------------------------------
('Accept-Encoding', 'gzip') ], 'cookie': [ ('cookie-name1', 'cookie-value1'), ('cookie-name2', 'cookie-value2'), ], 'outline-depth': 10, } pdfkit.from_file(htmls, file_name, options=options,configuration=config) def main(): start = time.time()
pdfs.append(file_name+str(i)+'.pdf')
file_name = u"liaoxuefeng_Python3_tutorial" urls = get_url_list() for index, url in enumerate(urls): parse_url_to_html(url, str(index) + ".html") htmls =[] pdfs =[] print(len(urls)) for i in range(len(urls)): htmls.append(str(i)+'.html') save_pdf(str(i)+'.html', file_name+str(i)+'.pdf')
output = open(u"廖雪峰Python_all.pdf", "wb")
print (u"转换完成第"+str(i)+'个html') print(pdfs) pdf_output = PdfFileWriter() for pdf in pdfs: pdf_input = PdfFileReader(open(pdf,'rb')) page_count = pdf_input.getNumPages() print(page_count) for i in range(page_count): pdf_output.addPage(pdf_input.getPage(i)) pdf_output.write(output) print (u"输出PDF成功!")
if not os.path.exists(dir_name):
for html in htmls: os.remove(html) print (u"删除临时文件"+html) for pdf in pdfs: os.remove(pdf) print (u"删除临时文件"+pdf) total_time = time.time() - start print(u"总共耗时:%f 秒" % total_time) #---------------------------------------------------------------------- def changeDir(dir_name): """ 目录切换 """ os.mkdir(dir_name)
main()
os.chdir(dir_name) #---------------------------------------------------------------------- if __name__ == '__main__': #存放文件的路径 dir_name = 'c:\\12'
changeDir(dir_name)

代码很简单,就是获取所有博客左侧导航栏对应的所有URL,然后将每个url解析出来保存成html,再将每个html保存成单个pdf文件,最后合并pdf文件。需要注意的是windwos 下需要安装wkhtmltopdf.exe 这个软件,并在python代码里指明这个程序的路径。不然合并时会报错。

下载html保存成pdf

de3dc9e87d60e4694b1a3fbfb12e85bd30e5e2a1

将单个html解析成单个pdf文件

合并成pdf

7df74128abd393796ba9f53f2bd322fa34ae1d9f

最后合并的文件

内容:

e202e2e588eeef7a36bc02ef11f03beff9fd1f70

最后的pdf文件

最新更新:按照这个代码目前无法抓取,因为廖老师把网站改成https了。对应代码要做修改。

而且Requests 请求里需要加入User-agent模拟浏览器请求,就可以了。


原文发布时间为:2018-11-25

本文作者:欧巴

本文来自云栖社区合作伙伴“Python爱好者社区”,了解相关信息可以关注“Python爱好者社区”。

相关文章
|
1月前
|
JSON C语言 C++
【Python 基础教程 26】Python3标准库全面入门教程:一步步带你深入理解与应用
【Python 基础教程 26】Python3标准库全面入门教程:一步步带你深入理解与应用
63 1
|
1月前
|
存储 安全 API
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
77 0
|
1月前
|
存储 算法 数据挖掘
【Python 基础教程 25】全面入门指南:深度解析Python3的命名空间,作用域及变量使用教程
【Python 基础教程 25】全面入门指南:深度解析Python3的命名空间,作用域及变量使用教程
54 0
|
1月前
|
存储 机器学习/深度学习 数据安全/隐私保护
【Python 基础教程 24】全面入门Python面向对象编程:深度探索与实战教程
【Python 基础教程 24】全面入门Python面向对象编程:深度探索与实战教程
79 0
|
1月前
|
Linux 数据库连接 C++
【Python 基础教程 23】Python3 错误与异常处理全面指南:从入门到精通的实用教程
【Python 基础教程 23】Python3 错误与异常处理全面指南:从入门到精通的实用教程
110 0
|
1月前
|
监控 API C语言
【Python 基础教程 22】全面揭秘Python3 os模块:从入门到高级的实用教程指南
【Python 基础教程 22】全面揭秘Python3 os模块:从入门到高级的实用教程指南
62 1
|
1月前
|
存储 前端开发 C++
【Python 基础教程 09】全面掌握Python3列表:从入门到精通的综合教程与实战指南
【Python 基础教程 09】全面掌握Python3列表:从入门到精通的综合教程与实战指南
90 1
|
1月前
|
JSON C++ 数据格式
【Python 基础教程 08】全面入门到精通:Python3 字符串操作实战教程与深度指南
【Python 基础教程 08】全面入门到精通:Python3 字符串操作实战教程与深度指南
86 0
|
1月前
|
机器学习/深度学习 数据采集 C++
【Python 基础教程 07】全面掌握Python3数字操作:入门到精通的实用指南
【Python 基础教程 07】全面掌握Python3数字操作:入门到精通的实用指南
85 2
|
1月前
|
Java 编译器 Shell
【Python 基础教程 04】超详细Python编程教程:初学者入门至全面了解Python 解析器( CPython、IPython、Jython和PyPy)
【Python 基础教程 04】超详细Python编程教程:初学者入门至全面了解Python 解析器( CPython、IPython、Jython和PyPy)
44 0