![](/img/trans.png)
[英]how to print the error message shown in a webpage - selenium python
[英]Python - Selenium - Print 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-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中進行一些設置以使其運行順暢,所以我想我會給出一個更全面的例子。 我認為僅僅是上面的評論中的訣竅,所以一些信用也應該去那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.