Reputation: 11
I have been using selenium to automatic printing documents and I am stuck on the print screen. As far as I know, selenium does not interact with the print screen so I am looking for an alternate situation that I can use with selenium. My code so far is down below, and all I need is code that will let me choose a new printer and then print. Also I want to change that printer to Save as PDF and then save the pdf to a file, so if that gives me a shortcut that would help a lot.
from selenium import webdriver
from selenium import *
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Remote(
command_executor='http://127.0.0.1:4444/wd/hub',
desired_capabilities=DesiredCapabilities.CHROME) #This is because I am using remote web driver for my Mac, but it is the same as regular web driver
driver.execute("window.print()")
#Need code here
Upvotes: 1
Views: 1430
Reputation: 103
I used window.print() followed by execution of a python string containing the necessary js commands:
print_function = '''
let A = document.getElementsByTagName('print-preview-app')[0].shadowRoot;
let B = A.getElementById('sidebar').children[0].shadowRoot;
let C = B.getElementById('button-strip').children[0]
C.click()
'''
driver.execute_script(print_function)
Keep in mind that you also need to use driver.swich_to.window(window_handles[i]) to make sure you're interacting with the print box.
Once you enter into a shadowRoot element, you don't have the full compliment of driver.find_element_by methods available to you. You're limited to the methods available via JS when you are searching within a shadowRoot.
Upvotes: 1
Reputation: 70
Found a suggestion that might work for you. How to convert webpage into PDF by using Python
Maybe try pdfkit
import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')
Upvotes: 0