【问题标题】:Python - Selenium - Print WebpagePython - Selenium - 打印网页
【发布时间】:2014-03-20 02:45:23
【问题描述】:

请问如何使用 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

【问题讨论】:

标签: python selenium python-3.x printing webpage


【解决方案1】:

虽然不是直接打印网页,但是很容易截取整个当前页面:

browser.save_screenshot("screenshot.png")

然后可以使用任何图像打印库打印图像。我个人没有使用过任何这样的库,所以我不能保证它,但快速搜索出现了win32print,看起来很有希望。

【讨论】:

    【解决方案2】:

    关键的“技巧”是我们可以在 selenium 浏览器窗口中使用 selenium webdriver 的“execute_script”方法执行 JavaScript,如果你执行 JavaScript 命令“window.print();”它将激活浏览器的打印功能。

    现在,要让它优雅地工作,需要设置一些首选项以静默打印、删除打印进度报告等。这是一个小而实用的示例,可以加载并打印您在最后一行中放置的任何网站(其中 '@ 987654321@'现在):

    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 中进行一些设置以使其运行顺畅,所以我想我会举一个更完整的例子。我认为诀窍就在上面的评论中,所以也应该有一些功劳。

    【讨论】:

    • 嗯,这已经有几年了,你能谈谈你尝试了什么以及发生了什么吗?是否产生了错误?
    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2015-04-10
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多