Skip to content

Commit 1fda2d4

Browse files
committed
init
1 parent a1a1cde commit 1fda2d4

7 files changed

Lines changed: 228 additions & 1 deletion

File tree

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
__pycache__/
33
*.py[cod]
44
*$py.class
5-
5+
.idea
66
# C extensions
77
*.so
88

README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#Python 爬虫:把廖雪峰的教程转换成 PDF 电子书
2+
3+
### 准备工具
4+
5+
requests、beautifulsoup 是爬虫两大神器,reuqests 用于网络请求,beautifusoup 用于操作 html 数据。有了这两把梭子,干起活来利索。scrapy 这样的爬虫框架我们就不用了,这样的小程序派上它有点杀鸡用牛刀的意思。此外,既然是把 html 文件转为 pdf,那么也要有相应的库支持, wkhtmltopdf 就是一个非常的工具,它可以用适用于多平台的 html 到 pdf 的转换,pdfkit 是 wkhtmltopdf 的Python封装包。首先安装好下面的依赖包
6+
7+
```python
8+
pip install requests
9+
pip install beautifulsoup
10+
pip install pdfkit
11+
```
12+
13+
### 安装 wkhtmltopdf
14+
Windows平台直接在 [http://wkhtmltopdf.org/downloads.html](http://wkhtmltopdf.org/downloads.html) 下载稳定版的 wkhtmltopdf 进行安装,安装完成之后把该程序的执行路径加入到系统环境 $PATH 变量中,否则 pdfkit 找不到 wkhtmltopdf 就出现错误 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令行进行安装
15+
16+
```shell
17+
$ sudo apt-get install wkhtmltopdf # ubuntu
18+
$ sudo yum intsall wkhtmltopdf # centos
19+
```
20+
21+
### 运行
22+
```python
23+
python crawler.py
24+
```
25+
26+
### 效果图
27+
![image](./crawer-pdf.png)
28+
29+
>作者:liuzhijun
30+
31+
>微信号: lzjun567
32+
33+
>公众号:一个程序员的微站(VTtalk)
34+
35+

crawer-pdf.png

149 KB
Loading

crawler.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# coding=utf-8
2+
import os
3+
import re
4+
import time
5+
6+
import pdfkit
7+
import requests
8+
from bs4 import BeautifulSoup
9+
10+
html_template = """
11+
<!DOCTYPE html>
12+
<html lang="en">
13+
<head>
14+
<meta charset="UTF-8">
15+
</head>
16+
<body>
17+
{content}
18+
</body>
19+
</html>
20+
21+
"""
22+
23+
24+
def parse_url_to_html(url, name):
25+
"""
26+
解析URL,返回HTML内容
27+
:param url:解析的url
28+
:param name: 保存的html文件名
29+
:return: html
30+
"""
31+
try:
32+
response = requests.get(url)
33+
soup = BeautifulSoup(response.content, "html5lib")
34+
# 正文
35+
body = soup.find_all(class_="x-wiki-content")[0]
36+
# 标题
37+
title = soup.find('h4').get_text()
38+
39+
# 标题加入到正文的最前面,居中显示
40+
center_tag = soup.new_tag("center")
41+
title_tag = soup.new_tag('h1')
42+
title_tag.string = title
43+
center_tag.insert(1, title_tag)
44+
body.insert(1, center_tag)
45+
html = str(body)
46+
# body中的img标签的src相对路径的改成绝对路径
47+
pattern = "(<img .*?src=\")(.*?)(\")"
48+
49+
def func(m):
50+
rtn = m.group(1) + "http://www.liaoxuefeng.com" + m.group(2) + m.group(3)
51+
return rtn
52+
53+
html = re.compile(pattern).sub(func, html)
54+
html = html_template.format(content=html)
55+
with open(name, 'wb') as f:
56+
f.write(html)
57+
return name
58+
59+
except Exception as e:
60+
print(e.message)
61+
62+
63+
def get_url_list():
64+
"""
65+
获取所有URL目录列表
66+
:return:
67+
"""
68+
response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000")
69+
soup = BeautifulSoup(response.content, "html5lib")
70+
menu_tag = soup.find_all(class_="uk-nav uk-nav-side")[1]
71+
urls = []
72+
for li in menu_tag.find_all("li"):
73+
url = "http://www.liaoxuefeng.com" + li.a.get('href')
74+
urls.append(url)
75+
return urls
76+
77+
78+
def save_pdf(htmls, file_name):
79+
"""
80+
把所有html文件保存到pdf文件
81+
:param htmls: html文件列表
82+
:param file_name: pdf文件名
83+
:return:
84+
"""
85+
options = {
86+
'page-size': 'Letter',
87+
'margin-top': '0.75in',
88+
'margin-right': '0.75in',
89+
'margin-bottom': '0.75in',
90+
'margin-left': '0.75in',
91+
'encoding': "UTF-8",
92+
'custom-header': [
93+
('Accept-Encoding', 'gzip')
94+
],
95+
'cookie': [
96+
('cookie-name1', 'cookie-value1'),
97+
('cookie-name2', 'cookie-value2'),
98+
],
99+
'outline-depth': 10,
100+
}
101+
pdfkit.from_file(htmls, file_name, options=options)
102+
103+
104+
def main():
105+
start = time.time()
106+
urls = get_url_list()
107+
file_name = u"liaoxuefeng_Python3_tutorial.pdf"
108+
htmls = [parse_url_to_html(url, str(index) + ".html") for index, url in enumerate(urls)]
109+
save_pdf(htmls, file_name)
110+
111+
for html in htmls:
112+
os.remove(html)
113+
114+
total_time = time.time() - start
115+
print(u"总共耗时:%f 秒" % total_time)
116+
117+
118+
if __name__ == '__main__':
119+
main()

file1.html

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
</head>
6+
<body>
7+
<div class="x-wiki-content">
8+
<p>这是小白的Python新手教程,具有如下特点:</p>
9+
<h1 id="-python-3-">中文,免费,零起点,完整示例,基于最新的Python 3版本。</h1>
10+
<p>Python是一种计算机程序设计语言。你可能已经听说过很多种流行的编程语言,比如非常难学的C语言,非常流行的Java语言,适合初学者的Basic语言,适合网页编程的JavaScript语言等等。</p>
11+
<p>那Python是一种什么语言?</p>
12+
<p>首先,我们普及一下编程语言的基础知识。用任何编程语言来开发程序,都是为了让计算机干活,比如下载一个MP3,编写一个文档等等,而计算机干活的CPU只认识机器指令,所以,尽管不同的编程语言差异极大,最后都得“翻译”成CPU可以执行的机器指令。而不同的编程语言,干同一个活,编写的代码量,差距也很大。</p>
13+
<p>比如,完成同一个任务,C语言要写1000行代码,Java只需要写100行,而Python可能只要20行。</p>
14+
<p>所以Python是一种相当高级的语言。</p>
15+
<p>你也许会问,代码少还不好?代码少的代价是运行速度慢,C程序运行1秒钟,Java程序可能需要2秒,而Python程序可能就需要10秒。</p>
16+
<p>那是不是越低级的程序越难学,越高级的程序越简单?表面上来说,是的,但是,在非常高的抽象计算中,高级的Python程序设计也是非常难学的,所以,高级程序语言不等于简单。</p>
17+
<p>但是,对于初学者和完成普通任务,Python语言是非常简单易用的。连Google都在大规模使用Python,你就不用担心学了会没用。</p>
18+
<p>用Python可以做什么?可以做日常任务,比如自动备份你的MP3;可以做网站,很多著名的网站包括YouTube就是Python写的;可以做网络游戏的后台,很多在线游戏的后台都是Python开发的。总之就是能干很多很多事啦。</p>
19+
<p>Python当然也有不能干的事情,比如写操作系统,这个只能用C语言写;写手机应用,只能用Swift/Objective-C(针对iPhone)和Java(针对Android);写3D游戏,最好用C或C++。</p>
20+
<p>如果你是小白用户,满足以下条件:</p>
21+
<ul>
22+
<li>会使用电脑,但从来没写过程序;</li>
23+
<li>还记得初中数学学的方程式和一点点代数知识;</li>
24+
<li>想从编程小白变成专业的软件架构师;</li>
25+
<li>每天能抽出半个小时学习。</li>
26+
</ul>
27+
<p>不要再犹豫了,这个教程就是为你准备的!</p>
28+
<p>准备好了吗?</p>
29+
<p><img src="http://liaoxuefeng/files/attachments/00138676512923004999ceca5614eb2afc5c0efdd2e4640000/0" alt="challenge-accepted"></p>
30+
<h3 id="-">关于作者</h3>
31+
<p><a href="http://weibo.com/liaoxuefeng" target="_blank">廖雪峰</a>,十年软件开发经验,业余产品经理,精通Java/Python/Ruby/Scheme/Objective C等,对开源框架有深入研究,著有《Spring 2.0核心技术与最佳实践》一书,多个业余开源项目托管在<a href="https://github.com/michaelliao" target="_blank">GitHub</a>,欢迎微博交流:</p>
32+
<p><a href="http://weibo.com/u/1658384301?s=6uyXnP" target="_blank"><img border="0" src="http://service.t.sina.com.cn/widget/qmd/1658384301/078cedea/2.png"></a></p>
33+
34+
</div>
35+
</body>
36+
</html>

file2.html

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>Title</title>
6+
</head>
7+
<body>
8+
<div class="x-wiki-content">
9+
<p>这是小白的Python新手教程,具有如下特点:</p>
10+
<h2 id="-python-3-">中文,免费,零起点,完整示例,基于最新的Python 3版本。</h2>
11+
<p>Python是一种计算机程序设计语言。你可能已经听说过很多种流行的编程语言,比如非常难学的C语言,非常流行的Java语言,适合初学者的Basic语言,适合网页编程的JavaScript语言等等。</p>
12+
<p>那Python是一种什么语言?</p>
13+
<p>首先,我们普及一下编程语言的基础知识。用任何编程语言来开发程序,都是为了让计算机干活,比如下载一个MP3,编写一个文档等等,而计算机干活的CPU只认识机器指令,所以,尽管不同的编程语言差异极大,最后都得“翻译”成CPU可以执行的机器指令。而不同的编程语言,干同一个活,编写的代码量,差距也很大。</p>
14+
<p>比如,完成同一个任务,C语言要写1000行代码,Java只需要写100行,而Python可能只要20行。</p>
15+
<p>所以Python是一种相当高级的语言。</p>
16+
<p>你也许会问,代码少还不好?代码少的代价是运行速度慢,C程序运行1秒钟,Java程序可能需要2秒,而Python程序可能就需要10秒。</p>
17+
<p>那是不是越低级的程序越难学,越高级的程序越简单?表面上来说,是的,但是,在非常高的抽象计算中,高级的Python程序设计也是非常难学的,所以,高级程序语言不等于简单。</p>
18+
<p>但是,对于初学者和完成普通任务,Python语言是非常简单易用的。连Google都在大规模使用Python,你就不用担心学了会没用。</p>
19+
<p>用Python可以做什么?可以做日常任务,比如自动备份你的MP3;可以做网站,很多著名的网站包括YouTube就是Python写的;可以做网络游戏的后台,很多在线游戏的后台都是Python开发的。总之就是能干很多很多事啦。</p>
20+
<p>Python当然也有不能干的事情,比如写操作系统,这个只能用C语言写;写手机应用,只能用Swift/Objective-C(针对iPhone)和Java(针对Android);写3D游戏,最好用C或C++。</p>
21+
<p>如果你是小白用户,满足以下条件:</p>
22+
<ul>
23+
<li>会使用电脑,但从来没写过程序;</li>
24+
<li>还记得初中数学学的方程式和一点点代数知识;</li>
25+
<li>想从编程小白变成专业的软件架构师;</li>
26+
<li>每天能抽出半个小时学习。</li>
27+
</ul>
28+
<p>不要再犹豫了,这个教程就是为你准备的!</p>
29+
<p>准备好了吗?</p>
30+
<p><img src="http://liaoxuefeng/files/attachments/00138676512923004999ceca5614eb2afc5c0efdd2e4640000/0" alt="challenge-accepted"></p>
31+
<h3 id="-">关于作者</h3>
32+
<p><a href="http://weibo.com/liaoxuefeng" target="_blank">廖雪峰</a>,十年软件开发经验,业余产品经理,精通Java/Python/Ruby/Scheme/Objective C等,对开源框架有深入研究,著有《Spring 2.0核心技术与最佳实践》一书,多个业余开源项目托管在<a href="https://github.com/michaelliao" target="_blank">GitHub</a>,欢迎微博交流:</p>
33+
<p><a href="http://weibo.com/u/1658384301?s=6uyXnP" target="_blank"><img border="0" src="http://service.t.sina.com.cn/widget/qmd/1658384301/078cedea/2.png"></a></p>
34+
35+
</div>
36+
</body>
37+
</html>

liaoxuefeng_Python3_tutorial.pdf

2.2 MB
Binary file not shown.

0 commit comments

Comments
 (0)