python抓取网页数据( Python数据结构模块安装及Python抓取实例讲述(组图))
优采云 发布时间: 2021-10-29 11:30python抓取网页数据(
Python数据结构模块安装及Python抓取实例讲述(组图))
Python实现抓取HTML网页并保存为PDF文件的方法
更新时间:2018-05-08 10:37:11 作者:Limerence
本文文章主要介绍Python抓取HTML网页并以PDF文件形式保存的方法,并以示例的形式分析PyPDF2模块的安装和Python抓取HTML页面并生成基于 PyPDF2 模块的 pdf 文件。相关操作技巧,有需要的朋友可以参考以下
本文介绍如何使用 Python 捕获 HTML 网页并将其保存为 PDF 文件。分享给大家,供大家参考,如下:
一、前言
今天的介绍是抓取HTML网页并保存为PDF。废话不多说,直接上教程吧。
今天的例子是以廖雪峰老师的Python教程网站为例:
二、准备工作
1. PyPDF2的安装和使用(用于合并PDF):
PyPDF2 版本:1.25.1
或
安装:
pip install PyPDF2
使用示例:
from PyPDF2 import PdfFileMerger
merger = PdfFileMerger()
input1 = open("hql_1_20.pdf", "rb")
input2 = open("hql_21_40.pdf", "rb")
merger.append(input1)
merger.append(input2)
# Write to an output PDF document
output = open("hql_all.pdf", "wb")
merger.write(output)
2. requests和beautifulsoup是爬虫的两大神器,reuqests用于网络请求,beautifulfusoup用于操作html数据。有了这两个穿梭机,工作顺利。我们不需要像scrapy这样的爬虫框架。这么小的程序有点大锤了。另外,既然是把html文件转换成pdf,就得有相应的库支持。 wkhtmltopdf 是一个非常有用的工具,可以用于多平台从html到pdf的转换。 pdfkit 是 wkhtmltopdf 的 Python 包。首先安装以下依赖包
pip install requests
pip install beautifulsoup4
pip install pdfkit
3. 安装 wkhtmltopdf
Windows平台直接下载稳定版wkhtmltopdf安装即可。安装完成后,将程序的执行路径添加到系统环境$PATH变量中,否则pdfkit将找不到wkhtmltopdf并出现“No wkhtmltopdf executable found”的错误提示。 Ubuntu 和 CentOS 可以直接从命令行安装
$ sudo apt-get install wkhtmltopdf # ubuntu
$ sudo yum intsall wkhtmltopdf # centos
三、数据准备
1. 获取每个文章
的url
def get_url_list():
"""
获取所有URL目录列表
:return:
"""
response = requests.get("http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000")
soup = BeautifulSoup(response.content, "html.parser")
menu_tag = soup.find_all(class_="uk-nav uk-nav-side")[1]
urls = []
for li in menu_tag.find_all("li"):
url = "http://www.liaoxuefeng.com" + li.a.get('href')
urls.append(url)
return urls
2. 通过 文章url
使用模板保存每个 文章 HTML 文件
html 模板:
html_template = """
{content}
"""
保存:
<p>
def parse_url_to_html(url, name):
"""
解析URL,返回HTML内容
:param url:解析的url
:param name: 保存的html文件名
:return: html
"""
try:
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 正文
body = soup.find_all(class_="x-wiki-content")[0]
# 标题
title = soup.find('h4').get_text()
# 标题加入到正文的最前面,居中显示
center_tag = soup.new_tag("center")
title_tag = soup.new_tag('h1')
title_tag.string = title
center_tag.insert(1, title_tag)
body.insert(1, center_tag)
html = str(body)
# body中的img标签的src相对路径的改成绝对路径
pattern = "(