该教程只提供了 HTML格式文件的下载,还是不太方便查阅,那就让我们动手将其转成PDF吧!
2、准备工作
2.1 软件安装
由于我们是要把html转为pdf,所以需要手动wkhtmltopdf 。Windows平台直接在 http://wkhtmltopdf.org/downloads.html 下载稳定版的 wkhtmltopdf 进行安装,安装完成之后把该程序的执行路径加入到系统环境 $PATH 变量中,否则 pdfkit 找不到 wkhtmltopdf 就出现错误 “No wkhtmltopdf executable found”。Ubuntu 和 CentOS 可以直接用命令行进行安装
$ sudo apt-get install wkhtmltopdf # ubuntu
$ sudo yum intsall wkhtmltopdf # centos
2.2 库安装
- pip install requests # 用于网络请求
- pip install beautifulsoup4 # 用于操作html
- pip install pdfkit # wkhtmltopdf 的Python封装包
- pip install PyPDF2 # 用于合并pdf
3、爬取内容
本文的目标网址为:http://python3-cookbook.readthedocs.io/zh_CN/latest/ 。
3.1 获取教程名称
页面的左边一栏为目录,按F12调出开发者工具并按以下步骤定位到目录元素:
① 点击开发者工具左上角"选取页面元素"按钮;
② 用鼠标点击左上角教程名称处。
通过以上步骤即可定位到目录元素,用图说明:
从图看到我们需要的教程名称包含在
<div class="wy-side-nav-search"></div>
之间的a
标签里。假设我们已经获取到了网页内容为html,可以使用以下代码获取该内容:
book_name = soup.find(‘div’, class_=‘wy-side-nav-search’).a.text