如何通过仅使用 Python 和 Selenium 直接上传文件来避免打开文件对话框?
How to avoid the open file dialog box by UPLOADING the file directly with Python and Selenium only?
我正在处理一个需要上传带有 "open file dialog" 文件的网站。
设置如下:
import selenium
from selenium import webdriver
browser = webdriver.Chrome(executable_path=r"C:\Users\PC\Documents\Downloads\chromedriver.exe")
browser.maximize_window()
filename = '24_bit_fixed.wav'
folder = 'C:\Users\PC\Documents\Downloads\'
path = folder + filename
这是棘手的部分:
NewRelease_Upload = '/html/body/ui-view/sections-list-modal/loeschen-modal/div/div[1]/div[3]/loeschen-modal-footer/button/div[1]/div[2]/span'
#browser.find_element_by_id("").send_keys(path)
#browser.find_element_by_xpath(NewRelease_Upload).send_keys(path)
我知道如果有一个 id,我可以很容易地使用这两行,从而避免打开文件对话框:
browser.switch_to_frame(0)
browser.find_element_by_id("something").send_keys(path)
但是网站上既没有 id 也没有这样的框架,我试图用 selenium
来做,没有 pywinauto
。
通常您不需要弄乱打开文件对话框。通常您需要做的就是找到 <input type="file">
元素。然后使用 elem.send_keys('fullfilename')
键入完整的文件名。然后提交表格。
如果您没有 id 来方便地查找元素(并且无法访问 html 以首先插入 id),那么您可以尝试使用其他方法查找该元素。例如使用 xpath //input[@type='file']
。这里还有更多:https://selenium-python.readthedocs.io/locating-elements.html
有时网站会弄乱输入元素,使其被隐藏或以其他方式混淆。那么你必须求助于更重的工具。
例如使用 javascript 到 "free" 首先输入元素:
或使用 javascript 在输入元素中键入文件名:Webdriver: File Upload
如果您需要帮助找到 <input type="file">
元素或输入文件名,请 post 另一个问题详细说明确切的问题和 post 相关的 html 源代码.
完整性:selenium 没有与文件打开对话框交互的功能。使用 <input type="file">
元素或使用 gui 自动化工具避免对话框。
我正在处理一个需要上传带有 "open file dialog" 文件的网站。
设置如下:
import selenium
from selenium import webdriver
browser = webdriver.Chrome(executable_path=r"C:\Users\PC\Documents\Downloads\chromedriver.exe")
browser.maximize_window()
filename = '24_bit_fixed.wav'
folder = 'C:\Users\PC\Documents\Downloads\'
path = folder + filename
这是棘手的部分:
NewRelease_Upload = '/html/body/ui-view/sections-list-modal/loeschen-modal/div/div[1]/div[3]/loeschen-modal-footer/button/div[1]/div[2]/span'
#browser.find_element_by_id("").send_keys(path)
#browser.find_element_by_xpath(NewRelease_Upload).send_keys(path)
我知道如果有一个 id,我可以很容易地使用这两行,从而避免打开文件对话框:
browser.switch_to_frame(0)
browser.find_element_by_id("something").send_keys(path)
但是网站上既没有 id 也没有这样的框架,我试图用 selenium
来做,没有 pywinauto
。
通常您不需要弄乱打开文件对话框。通常您需要做的就是找到 <input type="file">
元素。然后使用 elem.send_keys('fullfilename')
键入完整的文件名。然后提交表格。
如果您没有 id 来方便地查找元素(并且无法访问 html 以首先插入 id),那么您可以尝试使用其他方法查找该元素。例如使用 xpath //input[@type='file']
。这里还有更多:https://selenium-python.readthedocs.io/locating-elements.html
有时网站会弄乱输入元素,使其被隐藏或以其他方式混淆。那么你必须求助于更重的工具。
例如使用 javascript 到 "free" 首先输入元素:
或使用 javascript 在输入元素中键入文件名:Webdriver: File Upload
如果您需要帮助找到 <input type="file">
元素或输入文件名,请 post 另一个问题详细说明确切的问题和 post 相关的 html 源代码.
完整性:selenium 没有与文件打开对话框交互的功能。使用 <input type="file">
元素或使用 gui 自动化工具避免对话框。