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爱好者社区”。

相关文章
|
3月前
|
安全 JavaScript 开发者
Python 自动化办公神器|一键转换所有文档为 PDF
本文介绍一个自动化批量将 Word、Excel、PPT、TXT、HTML 及图片转换为 PDF 的 Python 脚本。支持多格式识别、错误处理与日志记录,适用于文档归档、报告整理等场景,大幅提升办公效率。仅限 Windows 平台,需安装 Office 及相关依赖。
194 0
|
1月前
|
索引 Python
Python 列表切片赋值教程:掌握 “移花接木” 式列表修改技巧
本文通过生动的“嫁接”比喻,讲解Python列表切片赋值操作。切片可修改原列表内容,实现头部、尾部或中间元素替换,支持不等长赋值,灵活实现列表结构更新。
115 1
|
2月前
|
数据采集 存储 XML
Python爬虫技术:从基础到实战的完整教程
最后强调: 父母法律法规限制下进行网络抓取活动; 不得侵犯他人版权隐私利益; 同时也要注意个人安全防止泄露敏感信息.
667 19
|
2月前
|
机器学习/深度学习 文字识别 Java
Python实现PDF图片OCR识别:从原理到实战的全流程解析
本文详解2025年Python实现扫描PDF文本提取的四大OCR方案(Tesseract、EasyOCR、PaddleOCR、OCRmyPDF),涵盖环境配置、图像预处理、核心识别与性能优化,结合财务票据、古籍数字化等实战场景,助力高效构建自动化文档处理系统。
651 0
|
3月前
|
程序员 数据安全/隐私保护 Python
1行Python代码,实现PDF的加密、解密
程序员晚枫分享使用python-office库实现PDF批量加密与解密的新方法。只需一行代码,即可完成单个或多个PDF文件的加密、解密操作,支持文件路径与正则筛选,适合自动化办公需求。更新至最新版,适配性更佳,操作更简单。
167 8
1行Python代码,实现PDF的加密、解密
|
2月前
|
数据采集 存储 JSON
使用Python获取1688商品详情的教程
本教程介绍如何使用Python爬取1688商品详情信息,涵盖环境配置、代码编写、数据处理及合法合规注意事项,助你快速掌握商品数据抓取与保存技巧。
|
3月前
|
并行计算 算法 Java
Python3解释器深度解析与实战教程:从源码到性能优化的全路径探索
Python解释器不止CPython,还包括PyPy、MicroPython、GraalVM等,各具特色,适用于不同场景。本文深入解析Python解释器的工作原理、内存管理机制、GIL限制及其优化策略,并介绍性能调优工具链及未来发展方向,助力开发者提升Python应用性能。
247 0
|
3月前
|
监控 Linux 数据安全/隐私保护
Python实现Word转PDF全攻略:从入门到实战
在数字化办公中,Python实现Word转PDF自动化,可大幅提升处理效率,解决格式兼容问题。本文详解五种主流方案,包括跨平台的docx2pdf、Windows原生的pywin32、服务器部署首选的LibreOffice命令行、企业级的Aspose.Words,以及轻量级的python-docx+pdfkit组合。每种方案均提供核心代码与适用场景,并涵盖中文字体处理、表格优化、批量进度监控等实用技巧,助力高效办公自动化。
900 0
|
数据安全/隐私保护 数据格式 Python
python爬取快手商品数据
python爬取快手商品数据
|
数据采集 前端开发 搜索推荐
python如何通过分布式爬虫爬取舆情数据
python如何通过分布式爬虫爬取舆情数据
python如何通过分布式爬虫爬取舆情数据

推荐镜像

更多
下一篇
oss云网关配置