学习Python中Selenium模块的基本用法(14:页面打印)
Selenium模块支持将网页输出为 PDF 文件,不需要调用操作系统的打印对话框,该功能允许通过代码自动化地生成网页的PDF快照。支撑打印功能的核心是PrintOptions类及print_page函数,前者用于设置页面打印的各类参数,而后者则不依赖于操作系统的打印对话框,直接通过浏览器的内置功能生成 PDF。
PrintOptions类的主要属性如下表所示:
序号 | 属性名 | 说明 |
---|---|---|
1 | orientation | 设置页面方向,取值包括landscape(横向)、 portrait(纵向) |
2 | page_ranges | 设置要打印的页码范围 ,官网文档中给出的示例都是字符串数组,可以是范围,也可以是具体页码集合,如[“1”, “2”, “3”] or [“1-3”],不过其它网站中给的例子也有用数值集合赋值 |
3 | page_height、page_width | 设置纸张高度和宽度 |
4 | margin_top 、margin_bottom 、margin_left、margin_right | 设置纸张上下左右方向的页边距 |
5 | scale | 设置页面的缩放比例 |
6 | background | 设置是否包含背景图形,取值包括True、False |
7 | shrink_to_fit | 设置是否缩放以适应页面 ,取值包括True、False |
设置PrintOptions类的打印参数后,将其传递给driver.print_page函数以便生成PDF,该函数返回Base64编码的字符串,解码后就是PDF文件的内容,最终按需保存为本地pdf文件。
以打印CSNN网站为例,主要代码如下所示:
import base64
from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptionsdriver = webdriver.Chrome()
driver.get("https://www.csdn.net/")print_options = PrintOptions()
print_options.orientation = "landscape"
print_options.shrink_to_fit = True
print_options.background = False
print_options.page_ranges =['1-2']# 打印页面并获取PDF内容(Base64编码)
pdf_base64 = driver.print_page(print_options=print_options)# 解码并保存PDF
pdf_bytes = base64.b64decode(pdf_base64)
with open("csdn.pdf", "wb") as f:f.write(pdf_bytes)driver.quit()
如果运行上述代码时报下面的错误,可能的原因是PrintOptions 类是在较新版本的Selenium中引入的,要想使用PrintOptions来打印页面,需要确保Selenium库是最新的,至少是Selenium 3.141.0及以上版本。
from selenium.webdriver.common.print_page_options import PrintOptions
ModuleNotFoundError: No module named 'selenium.webdriver.common.print_page_options'
参考文献:
[1]https://www.selenium.dev/zh-cn/
[2]https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/
[3]https://blog.csdn.net/kk_lzvvkpj/article/details/148610502
[4]https://registry.npmmirror.com/binary.html?path=chromedriver/
[5]https://chromedriver.chromium.org/