如何使用 Selenium 打印网页。
import time
from selenium import webdriver
# Initialise the webdriver
chromeOps=webdriver.ChromeOptions()
chromeOps._binary_location = "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
chromeOps._arguments = ["--enable-internal-flash"]
browser = webdriver.Chrome("C:\\Program Files\\Google\\Chrome\\Application\\chromedriver.exe", port=4445, chrome_options=chromeOps)
time.sleep(3)
# Login to Webpage
browser.get('www.webpage.com')
注意:我目前使用的是 Google Chrome 的当前版本:版本 32.0.1700.107 m
虽然不是直接打印网页,但很容易截取整个当前页面:
browser.save_screenshot("screenshot.png")
然后可以使用任何图像打印库打印图像。我个人没有使用过任何这样的库,所以我不一定能保证它,但快速搜索发现了win32print,看起来很有希望。
关键的“技巧”是我们可以使用selenium webdriver的“execute_script”方法在selenium浏览器窗口中执行JavaScript,如果执行JavaScript命令“window.print();”它将激活浏览器的打印功能。
现在,要让它优雅地工作,需要设置一些首选项以静默打印、删除打印进度报告等。这是一个小但实用的示例,它加载并打印您在最后一行中放置的任何网站(其中“http:”)。 //www.cnn.com/' 现在):
import time
from selenium import webdriver
import os
class printing_browser(object):
def __init__(self):
self.profile = webdriver.FirefoxProfile()
self.profile.set_preference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", False)
self.profile.set_preference("pdfjs.disabled", True)
self.profile.set_preference("print.always_print_silent", True)
self.profile.set_preference("print.show_print_progress", False)
self.profile.set_preference("browser.download.show_plugins_in_list",False)
self.driver = webdriver.Firefox(self.profile)
time.sleep(5)
def get_page_and_print(self, page):
self.driver.get(page)
time.sleep(5)
self.driver.execute_script("window.print();")
if __name__ == "__main__":
browser_that_prints = printing_browser()
browser_that_prints.get_page_and_print('http://www.cnn.com/')
您可能缺少的关键命令是“self.driver.execute_script(“window.print();”)”,但需要在init中进行一些设置才能使其运行顺利,所以我想我应该给一个更完整的例子。我认为技巧就在上面的评论中,所以也应该有一些功劳。
含硒 >= 4:
import base64
pdf = self.browser.print_page()
pdf_bytes = base64.b64decode(pdf)
with open(filepath, "wb") as fh:
fh.write(pdf_bytes)
请参阅 PR 了解 Python 绑定