selenium上传文件时打开指定本地文件路径

发布于:2024-04-30 ⋅ 阅读:(28) ⋅ 点赞:(0)

遇到这样一个问题:

用selenium和chromedriver操作浏览器,其中有一个“本地上传”的按钮,点击后,会进入本地电脑的文件夹,但是这个文件夹一般是C:\Users\XX。如何指定本地上传路径呢?

看起来很简单的一个问题,却没有想到如此复杂。

经过内外的一通搜索,终于实现。

参考文章如下:

How do I set Chrome upload directory with Selenium & VBA - Stack Overflow

c# - Where can I find a list of all available ChromeOption arguments? - Stack Overflow

Cannot Add Prefs as Experimental Option · Issue #524 · ultrafunkamsterdam/undetected-chromedriver · GitHub

https://mathsfromnothing.au/payroll-process-and-user-interface/?i=1

https://mathsfromnothing.au/payroll-process-and-user-interface/?i=2


注意一点:这个操作仅对webdriver.Chrome(options=chrome_options)有效,对undetected_chromedriver的uc.Chrome(chrome_options=chrome_options)无效。

代码如下:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

uploaddir="指定目录"
chrome_options = Options()
prefs = {'selectfile.last_directory' : str(pathlib.PureWindowsPath(uploaddir))}
chrome_options.add_experimental_option('prefs', prefs)

xxx_driver = webdriver.Chrome(options=chrome_options)
xxx_driver .maximize_window()

url="https://xxx.com"
xxx_driver .get(url)

# 本地上传
local_submit_button = WebDriverWait(xxx_driver, 5).until(
    EC.element_to_be_clickable((By.XPATH,'//button/span[contains(text(), "本地上传")]'))
)
# local_submit_button .click()#直接操作会报错:element click intercepted

webdriver.ActionChains(xxx_driver).move_to_element(local_submit_button ).click(local_submit_button ).perform()