我使用以下脚本将我的 png 图像上传到一个秘密网站:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import os
def select_image_for_tab(driver, image_file):
# Find and click on "Browse for a file" button
browse_button = driver.find_element(By.XPATH, "//button[text()='Browse for a file']")
browse_button.click()
# Wait for the file input to be visible and interactable
time.sleep(0.5)
# Handle the file upload dialog using Selenium
file_input = driver.find_element(By.XPATH, "//input[@type='file']")
file_input.send_keys(image_file)
# Wait for the file to be uploaded and the file selection dialog to close
WebDriverWait(driver, 20).until(EC.invisibility_of_element_located((By.XPATH, "//input[@type='file']")))
if __name__ == "__main__":
image_files_directory = r"E:\Desktop\social\Output_folder\folder 20"
# Prompt to focus on Firefox
print("Please focus on Firefox. The script will start in 5 seconds...")
time.sleep(5)
# Set up the Firefox driver
driver = webdriver.Firefox()
try:
# Open the website in a new tab
driver.get("UPLOAD_URL.com")
# Wait for the website to load and the target element to be clickable
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "(//div[@class='ms-Stack css-147']//div)[1]")))
# Click on the target element
target_element = driver.find_element(By.XPATH, "(//div[@class='ms-Stack css-147']//div)[1]")
target_element.click()
# Get a list of all PNG image files in the directory
image_files = [f for f in os.listdir(image_files_directory) if f.lower().endswith('.png')]
# Select image files for each tab
for image_file in image_files:
select_image_for_tab(driver, os.path.join(image_files_directory, image_file))
time.sleep(0.5) # Adjust this delay if needed
# Open a new tab and load the website in it
driver.execute_script("window.open('about:blank');")
driver.switch_to.window(driver.window_handles[-1])
driver.get("UPLOAD_URL.com")
# Wait for the website to load in the new tab and the target element to be clickable
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "(//div[@class='ms-Stack css-147']//div)[1]")))
time.sleep(4) # Additional wait time if needed
print("File selection completed for all tabs.")
except Exception as e:
print("An error occurred:", e)
finally:
# The script will not close the browser or any tabs after completion
pass
但每次我都必须将文件分成 20 个一组。
Firefox 无法处理超过 20 个选项卡。如何在远程 Firefox 中绕过此限制?
请注意:请不要询问秘密 URL 或 UPLOAD_URL.com
不需要答案,我找到了解决方案。
我必须使用
dom.popup_maximum
将 opts.set_preference("dom.popup_maximum", 50)
首选项设置为 50。然后我在使用 opts
初始化 webdriver.Firefox()
时必须使用 driver = webdriver.Firefox(options=opts)
。