Skip to content

Instantly share code, notes, and snippets.

@diegoquintanav
Last active March 26, 2022 15:13
Show Gist options
  • Save diegoquintanav/f10fd2dbbcb4708a8fa9282903336bb0 to your computer and use it in GitHub Desktop.
Save diegoquintanav/f10fd2dbbcb4708a8fa9282903336bb0 to your computer and use it in GitHub Desktop.
Move downloaded files to another folder using selenium
from pathlib import Path
import time
# adapted from https://stackoverflow.com/questions/23896625/how-to-change-default-download-folder-while-webdriver-is-running
def move_to_download_folder(
download_dir: Path,
new_destination_dir: Path,
lookup_str: str,
wait_seconds: int = 5,
max_tries: int = 3,
):
if download_dir in new_destination_dir.parents:
raise ValueError("new_destination should not be inside download_dir, otherwise data will be moved around recursively.")
# initialization
got_file = False
tries = 0
# grab current file name.
while not got_file:
matched_files: list[Path] = list(download_dir.glob(lookup_str))
if not matched_files:
if tries == max_tries:
print("Maximum number of tries reached. File was not found.")
break
else:
print(f"No file has been found. Perhaps it does not exist or it has not finished downloading yet. Waiting {wait_seconds} seconds to try again...")
tries += 1
time.sleep(wait_seconds)
continue
else:
print(f"Matched {len(matched_files)} files.")
got_file = True
# create dest dir if it does not exist
new_destination_dir.mkdir(exist_ok=True, parents=True)
# Create new file name
for file in matched_files:
filename = file.name # file.ext
new_file_destination = new_destination_dir.joinpath(filename) # new_dir/file.ext
print(f"Moving {file} to {new_file_destination}.")
file.rename(new_file_destination) # mv current_dir/file.ext new_dir/file.ext
return None
@diegoquintanav
Copy link
Author

while is bad, replace for a for loop if you can.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment