我已经成功使用上述脚本打印和下载PDF文件,但我遇到了一个问题,如何在Selenium Python中以横向模式输出打印/下载PDF文件。
我尝试使用pdfkit的“fromstring”与selenium “driver.getsource”,但是纵向模式的结果不太好,最终我选择使用chromedriver的打印PDF功能,并成功制作了所需的PDF文件,但仅限于纵向模式。即使我需要的是横向模式。
我尝试使用pdfkit的“fromstring”与selenium “driver.getsource”,但是纵向模式的结果不太好,最终我选择使用chromedriver的打印PDF功能,并成功制作了所需的PDF文件,但仅限于纵向模式。即使我需要的是横向模式。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import time
import pdfkit
import json
import os
curr_dir = os.getcwd()
download_path = os.path.join(curr_dir, 'dl')
appState = {
"recentDestinations": [
{
"id": "Save as PDF",
"origin": "local"
}
],
"selectedDestinationId": "Save as PDF",
"version": 2,
}
profile = {
'printing.print_preview_sticky_settings.appState': json.dumps(appState),
'savefile.default_directory': download_path,
}
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
chrome_options.add_argument('--kiosk-printing')
driver = webdriver.Chrome("D:\\master\\chromedriver\\2.45\\chromedriver.exe",
chrome_options=chrome_options)
URL = "taget site"
def site_login():
driver.get(URL)
driver.find_element_by_id('username').send_keys('username')
driver.find_element_by_id ('password').send_keys('pass')
driver.find_element_by_name('login').click()
def get_abc():
driver.get('https://targetsite/abc')
driver.find_element_by_name('year_id_combo')
s1 = Select(driver.find_element_by_name('year_id_combo'))
s1.select_by_visible_text('summer')
select_box = driver.find_element_by_name('course_id')
mk = [x for x in select_box.find_elements_by_tag_name("option")]
course_name = mk[2].text
course_name = course_name.replace(' ', '_')
index_mk = course_name.index('|')
course_name = course_name[:index_mk]
s2 = Select(driver.find_element_by_name('course_id'))
s2.select_by_value(mk[2].get_attribute('value'))
s3 = Select(driver.find_element_by_name('class'))
list_class = driver.find_element_by_name('class')
class = [x for x in list_class.find_elements_by_tag_name("option")]
s3.select_by_value(class[1].get_attribute('value'))
# multiple windows handle
main_window_handle = None
while not main_window_handle:
main_window_handle = driver.current_window_handle
driver.find_element_by_xpath( '/html/body/div[3]/div[2]/div/div/div[1]/div[1]/div/div[2]/div[2]/div/input[1]').click()
print_window_handle = None
while not print_window_handle:
for handle in driver.window_handles:
if handle != main_window_handle:
print_window_handle = handle
break
driver.switch_to.window(print_window_handle)
webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
driver.execute_script(
"document.title='{}';window.print();".format(course_name)
)
def logout_system():
driver.find_element_by_xpath('//a[normalize-
space(text())="Logout"]').click()
def close():
driver.close()
driver.quit()
site_login()
time.sleep(5)
get_abc()
time.sleep(70)
logout_system()
time.sleep(5)
close()
我希望结果以pdf横向模式打印,但是我不知道如何在这种情况下使其成为横向,目前的结果只是一个纵向的PDF。