1

在使用 Metamask 登录后,我正在尝试在OpenSea Create 页面中自动化一个过程,到目前为止,我已经设法开发了一个简单的程序,该程序使用传递给“打开文件”对话框的路径“隐含地选择特定图像文件” ",代码如下:

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)

输出:

预览0

查完网址后,程序点击相应按钮上传文件

预览1

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

预览2

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

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

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

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

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

PS:我必须以这种方式执行此过程,因为该send_keys()方法在此页面中不起作用

4

1 回答 1

1

您尝试与之交互的对话框是本机操作系统对话框,它不是一种浏览器处理程序/对话框/选项卡等。因此 Selenium 无法指示它并且无法处理它。有几种方法可以处理此类 OS 本机对话框。我不想复制 - 粘贴现有的解决方案。例如,您可以尝试解决方案。它非常详细,看起来不错。

于 2022-01-26T07:31:01.400 回答