Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-Selenium-Print网页_Python_Selenium_Python 3.x_Printing_Webpage - Fatal编程技术网

Python-Selenium-Print网页

Python-Selenium-Print网页,python,selenium,python-3.x,printing,webpage,Python,Selenium,Python 3.x,Printing,Webpage,如何使用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-in

如何使用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")
然后可以使用任何图像打印库打印图像。我个人没有使用过任何这样的库,所以我不一定能证明它,但是出现了一个快速搜索,看起来很有希望。

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

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


您可能缺少的关键命令是“self.driver.execute_script(“window.print();”),但需要在init中进行一些设置,以使其平稳运行,因此我想我会给出一个更完整的示例。我认为技巧就在上面的一条评论中,因此也应该有一些功劳。

您想获得html源代码:?或者你想要一个枯树版:?好吧,这已经有几年了,你能谈谈你的尝试和发生的事情吗?是否产生了错误?
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/')