Есть ли способ получить имя файла и местоположение из файла, который загружается селен и веб-драйвер - PullRequest
0 голосов
/ 02 июня 2019

У меня есть скрипт, который автоматизирует загрузку файла, используя селен и веб-драйвер в качестве Chrome в основном, он входит на рабочий сайт и нажимает на некоторые настройки, чтобы подготовиться к загрузке файла отчета, а затем нажимает кнопку загрузки

Есть ли способ для селена или любой другой библиотеки получить местоположение файла и имя того файла, который загружается или только что загружен, чтобы я мог сохранить его в переменной, чтобы использовать позже в скрипте

Я не знаю, будет ли работать относительный путь или ему нужно полное имя пути Windows, чтобы он работал ... вероятно, можно с уверенностью предположить, что полный путь более гарантированно будет работать

Пример: C: \ Users \ FunnyUserName \ Downloads \ report.xls

Добавление кода, чтобы показать, что происходит лучше

#For Report Pull
#-----------------------------------------------
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import datetime

import os
import glob






###############################################################
#Pull Report                                                  #
###############################################################




#Open Web Driver
browser = webdriver.Chrome()


#Open Website and Log in
print('Open Website and Log In')
browser.get(('https://SomeWebsite.com'))


print('Working on Getting the QC Report')
print('Please Stand By')

#####
#I Removed a lot of stuff not necessary to this question



#Get the File
WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="btnGenerateReport"]'))).click()


time.sleep(4)



#Working on getting the last downloaded Filename
# get the user download folder (dynamic so will work on any machine)
downLoadFolder =os.path.join( os.getenv('USERPROFILE'), 'Downloads')




print(downLoadFolder)
#This shows the correct folder....
#In My Case C:\Users\My UserName\Downloads



# get the list of files
list_of_files = glob.glob(downLoadFolder+"/*.*") # * means all if need specific formats (if you are looking for any specific format then specify eg: "/*.xls" to filter)


print (list_of_files)
#Always Shows ['C:\\Users\\My UserName\\Downloads\\desktop.ini']





# get the latest file name
#Forced the Folder and file type as a test
latest_file = max(glob.glob("C:/Users/My Username/Downloads/*.xls"), key=os.path.getctime)
#print the latest file name

print(latest_file)
#Returns:latest_file = max(glob.glob("C:/Users/My Username/Downloads/*.xls"), key=os.path.getctime)
#ValueError: max() arg is an empty sequence





Ответы [ 2 ]

0 голосов
/ 02 июня 2019

Я мог бы выяснить, где проблема

Мне нужно, чтобы получить фактический каталог загрузок, а не систему по умолчанию

Я тестирую на своем домашнем компьютере, он загружается по умолчанию в каталог загрузки Dropbox, который я также делю с моим рабочим компьютером

так что это не C: \ Users \ My Username \ Downloads \

это на самом деле D: \ Dropbox \ Downloads ... именно там в настоящее время установлен мой хром по умолчанию

как мне получить каталог загрузки chrome?

0 голосов
/ 02 июня 2019

Вот решение в питоне.

Требуется импорт:

import glob
import os

Скрипт:

# get the user download folder (dynamic so will work on any machine)
downLoadFolder =os.path.join( os.getenv('USERPROFILE'), 'Downloads')
# get the list of files
list_of_files = glob.glob(downLoadFolder+"/*") # * means all if need specific formats (if you are looking for any specific format then specify eg: "/*.xlsx" to filter)
# get the latest file name
latest_file = max(list_of_files, key=os.path.getctime)
#print the latest file name
print(latest_file)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...