17

有没有办法与 webdriver 中的文件上传框进行交互?放入路径的表单字段是只读的,所以我无法写入。

4

7 回答 7

21

您可以在不注入 JavaScript 的情况下执行此操作。您只需要获取表单字段并输入即可。类似于(使用 Ruby API):

driver.find_element(:id, 'upload').send_keys('/foo/bar')
于 2010-07-23T16:39:08.597 回答
11

您可以使用 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"),这也应该有效。

于 2010-07-22T08:40:46.383 回答
7

对于 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);
于 2015-07-20T14:07:58.180 回答
3

我发现的问题是上传对话框挂起 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。

于 2012-08-08T20:26:44.823 回答
1

我也在寻找第三方图书馆,

除非没有任何其他窗口然后这对我有用:

在 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}");
于 2018-10-08T12:06:33.100 回答
0

在我的情况下,我可以上传类似解决方案的文件,但对话窗口卡住了进程,驱动程序无法参考关闭此窗口,所以我手动杀死了他:

 foreach (var p in Process.GetProcessesByName("chrome"))
        if (p.MainWindowTitle.ToLower().Contains("open"))
               p.Kill();
于 2020-05-20T01:19:31.913 回答
-1

我们可以使用以下(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"

这有助于我上传图片。

于 2012-08-28T05:49:37.877 回答