在 Python 的 Chrome 浏览器选项卡中按下按钮后,如何检查“打开文件”对话框是否已打开?

How to check if Open File dialog has been open after pressing a button in a Chrome Browser tab on Python?

我正在尝试在使用 Metamask 登录后在 OpenSea Create page 中自动执行一个过程,到目前为止,我已经设法开发了一个简单的程序,该程序使用通过的路径选择特定的图像文件打开文件对话框“implicitly”,代码如下:

import pyautogui
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def wait_xpath(code): #function to wait for the xpath of an element to be located
    WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.XPATH, code)))


opt = Options() #the variable that will store the selenium options
opt.add_experimental_option("debuggerAddress", "localhost:9222") #this allows bulk-dozer to take control of your Chrome Browser in DevTools mode.
s = Service(r'C:\Users\ResetStoreX\AppData\Local\Programs\Python\Python39\Scripts\chromedriver.exe') #Use the chrome driver located at the corresponding path
driver = webdriver.Chrome(service=s, options=opt) #execute the chromedriver.exe with the previous conditions

nft_folder_path = r'C:\Users\ResetStoreX\Pictures\Cryptobote\Cryptobote NFTs\Crypto Cangrejos\SANDwich\Crabs'
start_number = 3


if driver.current_url == 'https://opensea.io/asset/create':
    print('all right')
    print('')
    print(driver.current_window_handle)
    print(driver.window_handles)
    print(driver.title)
    print('')
    nft_to_be_selected = nft_folder_path+"\"+str(start_number)+".png"
    wait_xpath('//*[@id="main"]/div/div/section/div/form/div[1]/div/div[2]')
    imageUpload = driver.find_element(By.XPATH, '//*[@id="main"]/div/div/section/div/form/div[1]/div/div[2]').click() #click on the upload image button
    print(driver.current_window_handle)
    print(driver.window_handles)
    time.sleep(2)
    pyautogui.write(nft_to_be_selected) 
    pyautogui.press('enter', presses = 2)

输出:

勾选URL后,程序点击相应按钮上传文件

然后等待 2 秒,然后将图像路径粘贴到 Name 文本框,然后按 Enter

所以文件最终被正确上传到这个页面。

事实是,上面的程序之所以有效,是因为在执行之前满足了以下条件:

  1. 当前 window 打开的是 Chrome 浏览器选项卡(而不是 Python 程序本身,即我的 Spyder 环境)
  2. 点击按钮上传文件后,默认选择 Name 文本框,而不管它打开的当前路径。

所以,我是个完美主义者,我想知道是否有一种方法(使用 Selenium 或其他 Python 模块)在执行之前检查是否有 Open File dialog 打开剩下的工作。

我在单击该按钮后立即尝试了 print(driver.window_handles),但是 Selenium 没有将 Open File dialog 识别为另一个 Chrome Window,它只是打印了这个的标签 ID页面,所以在我看来 Selenium 不能做我想做的事,但我不确定,所以我想听听在这种情况下可以使用哪些其他方法。

PS: 我不得不这样做,因为send_keys()方法在这个页面中不起作用

您尝试与之交互的对话框是本机 OS 对话框,它不是一种浏览器处理程序/对话框/选项卡等。因此 Selenium 无法指示它也无法处理它。有多种方法可以使用此类 OS 本机对话框。我不想复制-粘贴现有的解决方案。例如,您可以尝试 this 解决方案。做工精细,看起来不错。