【问题标题】:Selenium: Upload file in Google ChromeSelenium:在 Google Chrome 中上传文件
【发布时间】:2012-03-12 10:03:19
【问题描述】:

由于 Selenium RC "attach_file" 仅支持 *Firefox,有什么方法可以在 Google Chrome 中上传文件?非常感谢任何建议或解决方法。

【问题讨论】:

标签: python selenium webdriver


【解决方案1】:

如果您使用的是 Webdriver,那么您只需使用“sendKeys”输入文件路径即可上传文件。您需要“跳过”单击打开对话框以选择文件的浏览按钮的部分。适合我的 Java 版本如下所示,

WebElement inputFilePath = driver.findElement(By.id("filepath"));
inputFilePath.sendKeys("/absolute/path/to/my/local/file");

【讨论】:

  • 可能还值得注意的是,使用 sendKeys 上传文件仅适用于
【解决方案2】:

上传文件通常是一个 POST 请求,所以你实际上可以不使用 Selenium 上传文件;除非您的网站需要 cookie,否则您需要先使用 webdriver.get_cookies() 重建 cookie

一个简单的例子:

# required package:
#   http://pypi.python.org/pypi/MultipartPostHandler/0.1.0

import MultipartPostHandler, urllib2, cookielib

cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),
                              MultipartPostHandler.MultipartPostHandler)

path_to_file = r"abc.zip"

open_file = open(path_to_file,"rb")
param = { "file": open_file }
req = opener.open("http://www.yoursite.com/uploadfile", param)
open_file.close()

【讨论】:

    【解决方案3】:

    使用 IJavaScriptExecutor 是将上传输入字段更改为可点击,因此 chrome 驱动程序不会弹出错误说此元素不可点击。

            [SetUp]
            public void SetupTest()
            {
                driver = new ChromeDriver();
                baseURL = "";
                verificationErrors = new StringBuilder();
            }
    
            [Test]
            public void Test()
            {
                IJavaScriptExecutor js = driver as IJavaScriptExecutor;
                IWebElement element = driver.FindElement(By.Id("UploadFile_ButtonID"));
                js.ExecuteScript("arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1", element);
                Thread.Sleep(1000);
                element.SendKeys("D:\\path\\test\\image.jpg");
    }
    

    【讨论】:

    • 没有上下文的代码是没有意义的。您还没有解释为什么要使用 JavaScript 执行器将元素设置为可见,恕我直言,这可能是不好的做法。 Selenium 会阻止您与隐藏元素进行交互,因为这是最终用户无法做到的。与其盲目地使用 JavaScript 来强制元素可见,您实际上应该做最终用户会做的事情来使元素可见。
    • 您还使用 Thread.sleep 这又是一种不好的做法,正确的做法是使用 WebDriverWait 对象和 ExpectedConditions 类来等待元素变得可见。这是一个粗制滥造的例子,没有任何解释和糟糕的代码实践 -1
    猜你喜欢
    • 2020-04-16
    • 2011-05-04
    • 2011-02-09
    • 2016-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2021-01-26
    相关资源
    最近更新 更多