如何点击<input type=file>跨浏览器使用 Selenium Webdriver? [英] How to click on <input type=file> across browsers using Selenium Webdriver?

查看:33
本文介绍了如何点击<input type=file>跨浏览器使用 Selenium Webdriver?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Selenium 2 - WebDriver 处理文件选择器对话框.信不信由你,我的问题不是处理操作系统原生文件选择器.那部分我能搞定!

I'm working on dealing with a file-chooser dialog using Selenium 2 - WebDriver. Believe it or not, my problem is NOT dealing with the OS-native file-chooser. That part I can handle!

问题是让 Selenium 正确点击选择文件"按钮.由于原始源 html 只是 ,浏览器决定如何将其呈现为字段和按钮.因此,按钮的位置和命名会因浏览器而异.我已经让它在 Chrome 中工作了,但这只是因为 Chrome 将按钮放在最左边的对齐方式上,而 Selenium 碰巧在默认情况下点击了那里.

The problem is getting Selenium to properly click on the "Choose File" button. Since the original source html is simply <input type='file'>, the browser determines how to render it as a field and a button. As a result, the placement and naming of the button changes depending on browser. I've got it working in Chrome, but only because Chrome places the button on the leftmost alignment and Selenium happens to click there by default.

有什么想法吗?我不清楚这种类型的输入是否真的可以从 DOM 内导航......

Any ideas? It's not clear to me if an input of this type is truly navigable from within the DOM anyway...

推荐答案

在任何操作系统上上传文件的正确方法是

The proper way to upload a file on any OS is to

  1. 找到 元素.您无需担心不同的实现和精确定位.只需找到元素,例如通过 xpath //input[@type='file']
  2. sendKeys()type()(或任何以您的语言将文本写入元素的方法)该输入元素的文件路径.
  1. Find the <input type='file'> element. You need not to worry about different implementations and exact positioning. Just find the element for example by xpath //input[@type='file']
  2. sendKeys() or type() (or whatever method writes text into elements in your language) the path to file to that input element.

示例 Java 代码:

Sample Java code:

// find the input element
WebElement elem = driver.findElement(By.xpath("//input[@type='file']"));
// 'type' the file location to it as it were a usual <input type='text' /> element
elem.sendKeys("C://path/To/File.jpg");

这适用于 WebDriver 中的每个操作系统和浏览器.

This works on every OS and browser in WebDriver.

这篇关于如何点击&lt;input type=file&gt;跨浏览器使用 Selenium Webdriver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆