Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

python - How to change default download folder while webdriver is running?

I am downloading several different data sets and would like each file (or set) to download to a specific folder. I have learned how to change the download directories at these page:

setting Chrome preferences w/ Selenium Webdriver in Python

Change the default chrome download folder webdriver C#

The problem is these methods only allow me to change the download directory when I open the webdriver. It takes a while to get to the download page so doing this is an ineffective solution. I've tried set preferences but I'm working with selenium webdriver and chrome in python and I have not been able to find anything on SO or in the python help. Even switching the window handle on a new driver won't work because it cannot grab another driver's already open window.

The link for the download site is customized so can't copy and paste into a new driver either. So far I've been using the os. module to get the name of each new file coming in but even this is unreliable because of varying download times.

If anyone has any idea on how to change the default settings to a webdriver while the webdriver is running that would be great. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the past, I have solved this by downloading to a temp folder and then renaming the file to the appropriate folder with something along the line of this:

def move_to_download_folder(downloadPath, newFileName, fileExtension):
    got_file = False   
    ## Grab current file name.
    while got_file = False:
        try: 
            currentFile = glob.glob(DOWNLOAD_PATH+"*"+fileExtension)
            got_file = True

        except:
            print "File has not finished downloading"
            time.sleep(20)

    ## Create new file name
    fileDestination = downloadPath+newFileName+fileExtension

    os.rename(currentFile, fileDestination)

    return

## Click element to download file
inputElement=driver.find_element_by_xpath("{xpath here}").click()

move_to_download_folder(downloadPath, newFileName, fileExtension)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...