Взаимодействие с окном «Сохранить как» при загрузке веб-страницы в Chrome с использованием SeleniumPython

Программы на Python
Ответить
Anonymous
 Взаимодействие с окном «Сохранить как» при загрузке веб-страницы в Chrome с использованием Selenium

Сообщение Anonymous »

У меня есть два скрипта:

Код: Выделить всё

# some stuff is done here and a list of urls is created such as:

urls = ['https://www.walmart.com/ip/Sabrina-Carpenter-Cherry-Pop-EDP-30ml-1oz/5492571361?classType=REGULAR&athbdg=L1600', 'https://www.walmart.com/ip/Hoey-5-1-Painless-Hair-Remover-Women-Facial-Removal-Electric-Cordless-Shaver-Set-Wet-Dry-Lady-Razor-Women-Bikini-Line-Nose-Hair-Eyebrow-Arm-Leg-USB-R/647670434?classType=REGULAR']

# Then, the script runs another script called get_url.py and passes the urls to it to be processed:
subprocess.Popen(['python', 'get_url.py', str(urls)])

#it is important that this does not block the code and the rest of the code in this script can run without waiting for get_url.py to  complete.
  • Код: Выделить всё

    get_url.py
    , вызванный выше, выглядит следующим образом и загружает каждый переданный ему URL-адрес:

Код: Выделить всё

import pandas as pd
import os
import time
from datetime import datetime
import pyautogui
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from concurrent.futures import ProcessPoolExecutor

def get_page(url):
file_name = f"{url[:20]}_{pd.to_datetime(datetime.now()).strftime('%Y-%m-%d %H-%M-%S')}.html"
file_path = os.path.join(os.getcwd(), 'data', 'htmls')
path_and_name = os.path.join(file_path, file_name)

driver = webdriver.Chrome(options=options)
driver.get(url)

time.sleep(1)
pyautogui.hotkey('ctrl', 's') # open the save as window
time.sleep(1)
pyautogui.typewrite(path_and_name ) # enter the path and file name so the webpage is downloaded in the desired directory
time.sleep(.5)
pyautogui.hotkey('enter')
time.sleep(.2)

while True: # wait until the download is complete, then close the driver
files = os.listdir(file_path)
if file_name in files:
driver.close()
break
time.sleep(.1)

urls = sys.argv[1] # getting urls from other.py
#converting the string urls to an actual list:
urls = ast.literal_eval(page_urls.replace('[', '').replace(']', '').replace('\n', ', '))

if __name__ =='__main__': # multi-processing the urls to speed up things(necessary)
with ProcessPoolExecutor(max_workers=10) as executer:
executer.map(get_page, urls, chunksize = 1)
Функция работает нормально, пока я открываю один браузер. Однако, как только ProcessPoolExecutor открывает несколько окон, оказывается, что часть функции pyautogui.typewrite теряет отслеживание окон, что может привести к тому, что path_and_name будет введен несколько раз. в окне «Сохранить как» или ввести неполное значение, что приводит к тому, что страница не загружается или загружается с неправильным именем/каталогом. Хуже того, если я щелкну где-нибудь, например, внутри моего редактора кода, когда функция запущена, pyautogui может ввести значение path_and_name в редакторе, где курсор активен. Запуск браузера в «безголовом» режиме, чтобы случайно не возиться с окнами, не помогает.
Итак, как мне исправить приведенный выше код?>

Подробнее здесь: https://stackoverflow.com/questions/792 ... rome-using
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»