У меня есть куча файлов трассировки, которые я пытаюсь каталогизировать.Идея состоит в том, чтобы открыть каждый из них с помощью «chrome: // tracing», а затем сохранить скриншот.Скриншоты легко каталогизировать.
Вот процесс:
- start chrome = works
- open "chrome: // tracing" = works
- открыть файл <== отсутствует часть <- мне нужна помощь с </li>
- сохранить скриншот = работает
Есть два способа открыть файл в chrome: // tracing:
a) - используйте кнопку «загрузить», перейдите к файлу и откройте «Обновление»: я смог найти и нажать кнопку «Загрузить» с помощью Selenium
Now - need to handle the file open / loading ??
b) - перетащитьи перетащите файл трассировки в основную часть окна - откройте его [понятия не имею, как это сделать ..]
Вот фактический код, который у меня есть:
from selenium import webdriver
driver = webdriver.Chrome() # Optional argument, if not specified will search path
driver.get("chrome://tracing");
time.sleep(2) # Let the user actually see something
# Find load button
# or drop file to main window ?
# Send the file location to the button
file_location = 'C:\........json'
driver.send_keys(file_location) # don't know where to sent it :: idea from https://towardsdatascience.com/controlling-the-web-with-python-6fceb22c5f08
time.sleep(15) # some files are big - might take 15 seconds to load
date_stamp = str(datetime.datetime.now()).split('.')[0]
date_stamp = date_stamp.replace(" ", "_").replace(":", "_").replace("-", "_")
file_name = date_stamp + ".png"
driver.save_screenshot(file_name)
После некоторых исследований, проб и ошибок вот мой окончательный (?) Рабочий код
- , расположенный на кнопке «Загрузить» и открывший диалог открытия файла
- использовал pywinauto, чтобы позаботитьсясвязь с диалоговым окном Open
- сохранил скриншот - используя уникальное имя файла, сгенерированное из метки даты
import time
from selenium import webdriver
from pywinauto.application import Application
import datetime
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
driver = webdriver.Chrome(chrome_options=options)
driver.get("chrome://tracing");
time.sleep(2)
# Find load button
sdomele = driver.find_element_by_tag_name("tr-ui-timeline-view")
ele = driver.execute_script("return arguments[0].shadowRoot;",sdomele)
button_found = ele.find_element_by_id("load-button")
button_found.click() # let's load that file
time.sleep(3)
# here comes the pywinauto part to take care communication with the Open file dialog
app = Application().connect(title='Open') # connect to an existing window
dlg = app.window(title='Open') # communicate with this window
#file_location = os.path.join(submission_dir, folder, file_name)
file_location = "C:\\FILES2OPEN\\file01.json"
app.dlg.type_keys(file_location) # txt goes to the "File Name" box
time.sleep(2) #type is slow - this is just for safety
app.dlg.OpenButton.click() # click the open button
time.sleep(15) # some files might be big
# generate filename based on current time
date_stamp = str(datetime.datetime.now()).split('.')[0]
date_stamp = date_stamp.replace(" ", "_").replace(":", "_").replace("-", "_")
file_name = date_stamp + ".png"
driver.save_screenshot(file_name) # save screenshot (just the "inner" part of the browser window / not a full screenshot)
time.sleep(2)
driver.quit()