有没有办法与 webdriver 中的文件上传框进行交互?放入路径的表单字段是只读的,所以我无法写入。
7 回答
您可以在不注入 JavaScript 的情况下执行此操作。您只需要获取表单字段并输入即可。类似于(使用 Ruby API):
driver.find_element(:id, 'upload').send_keys('/foo/bar')
您可以使用 JavaScript 设置输入字段的值。考虑到该字段的 id 是fileName
以下示例,将输入的值设置为文件C:\temp\file.txt
:
String script = "document.getElementById('fileName').value='" + "C:\\\\temp\\\\file.txt" + "';";
((IJavaScriptExecutor)driver).ExecuteScript(script);
在此示例中,driver
是您的 WebDriver 实例。
请注意,\
对于类似 Windows 的路径,您必须使用四个反斜杠 ( ),因为您需要将双反斜杠传递给 JavaScript,因此您必须使用两个额外的斜杠对两者进行转义。另一种选择是使用正斜杠(例如"C:/tmp/file.txt"
),这也应该有效。
对于 C#,SendKeys()
有效,但您必须\
在文件路径中使用,而不是/
例如,以下作品:
string filePath = @"drive:\path\filename.filextension";
driver.FindElement(By.Id("fileInput")).SendKeys(filePath);
但以下不起作用:
string filePath = "drive:/path/filename.filextension";
driver.FindElement(By.Id("fileInput")).SendKeys(filePath);
我发现的问题是上传对话框挂起 webdriver 直到关闭。也就是说,调用上传对话框的element.click在上传对话框关闭之前不会返回。需要明确的是,上传对话框意味着操作系统原生文件选择。
这是我的解决方案(它有点复杂,但 *耸耸肩* selenium webdriver 问题的大多数解决方法必须变得复杂)。
# presumes webdriver has loaded the web page of interest
element_input = webdriver.find_element_by_css_selector('input[id="uploadfile"]')
handle_dialog(element_input, "foobar.txt")
def handle_dialog(element_initiating_dialog, dialog_text_input):
def _handle_dialog(_element_initiating_dialog):
_element_initiating_dialog.click() # thread hangs here until upload dialog closes
t = threading.Thread(target=_handle_dialog, args=[element_initiating_dialog] )
t.start()
time.sleep(1) # poor thread synchronization, but good enough
upload_dialog = webdriver.switch_to_active_element()
upload_dialog.send_keys(dialog_text_input)
upload_dialog.send_keys(selenium.webdriver.common.keys.Keys.ENTER) # the ENTER key closes the upload dialog, other thread exits
在 Ubuntu 12 上使用 python 2.7、webdriver 2.25.0 和 firefox。
我也在寻找第三方图书馆,
除非没有任何其他窗口然后这对我有用:
在 C# 中添加对 System.Windows.Forms 的引用
using System.Windows.Forms;
string url = "http://nervgh.github.io/pages/angular-file-upload/examples/image-preview/";
string path = @"C:\Users\File_Path";
IWebDriver d = new ChromeDriver();
d.Navigate().GoToUrl(url);
d.FindElement(By.XPath("//input[@type='file']")).Click();
hread.Sleep(5000);
System.Windows.Forms.SendKeys.SendWait(path);
System.Windows.Forms.SendKeys.SendWait(@"{Enter}");
在我的情况下,我可以上传类似解决方案的文件,但对话窗口卡住了进程,驱动程序无法参考关闭此窗口,所以我手动杀死了他:
foreach (var p in Process.GetProcessesByName("chrome"))
if (p.MainWindowTitle.ToLower().Contains("open"))
p.Kill();
我们可以使用以下(ruby API)
@driver.find_element(:xpath, "html/body/div[1]/div[2]/div[1]/form/div[4]/div[7]/table/tbody/tr[1]/td[2]/input").send_keys "C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg"
这有助于我上传图片。