簡體   English   中英

如何通過使用 Selenium Grid 將文件從本地機器傳輸到遠程 web 服務器來上傳文件

[英]How to upload a file by transfering the file from the local machine to the remote web server using Selenium Grid

使用 Selenium 網格上傳文件:

代碼

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Main 
{
    
    public static void main(String[] args) throws MalformedURLException
    {
          DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
          capabilities.setBrowserName("internet explorer");
    
          RemoteWebDriver driver = new RemoteWebDriver(new URL("http://URL:4444/wd/hub"), capabilities);
          driver.setFileDetector(new LocalFileDetector());
          driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    
          driver.get("https://url.de/index.xhtml");
          driver.findElement(By.xpath("//*[@id='form:sdsupload']/span")).click();
        
          WebElement addFile = driver.findElement(By.xpath("//input[@type='file']"));
          ((RemoteWebElement) addFile ).setFileDetector(new LocalFileDetector());
          addFile.sendKeys("C:\\daten\\test\\test2.xml");
    }
}

例外

Jun 26, 2020 3:47:43 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Detected dialect: W3C
Exception in thread "main" org.openqa.selenium.InvalidArgumentException: Attempting to upload file 'C:\daten\test\test2.xml' which does not exist.
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'xxx', ip: 'xxx', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, browserName: internet explorer, browserVersion: 11, javascriptEnabled: true, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), se:ieOptions: {browserAttachTimeout: 0, elementScrollBehavior: 0, enablePersistentHover: true, ie.browserCommandLineSwitches: , ie.ensureCleanSession: false, ie.fileUploadDialogTimeout: 3000, ie.forceCreateProcessApi: false, ignoreProtectedModeSettings: false, ignoreZoomSetting: false, initialBrowserUrl: http://localhost:5494/, nativeEvents: true, requireWindowFocus: false}, setWindowRect: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, webdriver.remote.sessionid: ae053a22-c088-402e-8de1-f25...}
Session ID: ae053a22-c088-402e-8de1-f25c4398ccbf
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:106)
    at de.xxx.xxx.keywords.Main.main(Main.java:41)

該文件存在於本地節點上,但不存在於遠程節點上。 如果該文件位於遠程節點上,則效果很好。 該文件存在於本地節點上,但不在遠程節點上: https://i.stack.imgur.com/f31Wb.png

我讀到這個:

如何將文件傳遞到遠程節點?

編輯

Firefox、IE 和 Edge Chromium 出現相同的錯誤

Firefox:

Exception in thread "main" org.openqa.selenium.InvalidArgumentException: File not found: C:\daten\test\test3.xml
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'xxx', ip: 'xxx', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_171'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: true, browserName: firefox, browserVersion: 60.5.0, javascriptEnabled: true, moz:accessibilityChecks: false, moz:geckodriverVersion: 0.25.0, moz:headless: false, moz:processID: 624, moz:profile: C:\Users\username\Ap..., moz:useNonSpecCompliantPointerOrigin: false, moz:webdriverClick: true, pageLoadStrategy: normal, platform: XP, platformName: XP, platformVersion: 10.0, rotatable: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, webdriver.remote.sessionid: 8801c61e-6d61-488b-8f86-c0a...}
Session ID: 8801c61e-6d61-488b-8f86-c0a1fb2f2df8
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122)
    at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:285)
    at org.openqa.selenium.remote.RemoteWebElement.sendKeys(RemoteWebElement.java:106)
    at de.xxx.xxx.keywords.Main.main(Main.java:52)

當我將文件復制到遠程客戶端時,它再次運行良好:(

調試:使用 Firefox 進行調試

此錯誤消息...

Exception in thread "main" org.openqa.selenium.InvalidArgumentException: Attempting to upload file 'C:\daten\test2.xml' which does not exist.

...表示客戶端計算機上不存在所需的文件。


本地文件檢測器

本地文件檢測器允許將文件從客戶端機器傳輸到遠程服務器。 如果測試需要將文件上傳到 web 應用程序,遠程WebDriver可以在運行時自動將文件從本地機器傳輸到遠程 web 服務器。 這允許從運行測試的遠程機器上載文件。 默認不啟用,可以如下啟用:

  • Java

     driver.setFileDetector(new LocalFileDetector());
  • Python

     from selenium.webdriver.remote.file_detector import LocalFileDetector driver.file_detector = LocalFileDetector()
  • C#

     var allowsDetection = this.driver as IAllowsFileDetection; if (allowsDetection.= null) { allowsDetection;FileDetector = new LocalFileDetector(); }
  • Ruby

     @driver.file_detector = lambda do |args| # args => ["/path/to/file"] str = args.first.to_s str if File.exist?(str) end
  • JavaScript

     var remote = require('selenium-webdriver/remote'); driver.setFileDetector(new remote.FileDetector);
  • Kotlin

     driver.fileDetector = LocalFileDetector()

這個用例

如果您在Selenium Grid上運行測試,那么您需要讓遠程驅動程序知道需要上傳的文件位於本地計算機上而不是遠程計算機上。 在這些情況下,要將文件從客戶端機器上傳到遠程服務器, WebDriver可以在運行時自動將文件從本地機器傳輸到遠程 web 服務器,您可以使用以下代碼塊:

WebElement addFile = driver.findElement(By.xpath("//input[@type='file']"));
((RemoteWebElement)addFile).setFileDetector(new LocalFileDetector());
addFile.sendKeys("C:\\daten\\test2.xml");

奧特羅

在 Selenium Grid 上運行測試時選擇和上傳文件

感謝@DebanjanB 幫助我找到解決方案 - 我贊成您的回復,這是對 state 的另一個答案,它確實有效。

我的問題:

在本地,我正在針對本地運行的 Selenium 服務器運行 Selenium 測試(運行selenium-server-4.0.0-beta-4.jar chromedriver.exe ,並且也使用了 Chrome 驅動程序文件。)

我使用以下方式上傳文件的測試(用 TypeScript 編寫):

await (
  await driver.findElement(By.xpath("//form//input[@id='upload-input']"))
).sendKeys(join(__dirname, "testfile.txt"));

在本地運行沒有問題。 但是在我們的 DevOps 管道中,使用selenium/standalone-chrome映像運行 Docker,就像驅動程序找不到文件一樣:

InvalidArgumentError: invalid argument: File not found: /home/vsts/work/1/s/selenium/tests/flows/testfile.txt

即使我們已經通過運行確認文件確實在正確的文件夾中找到:

> pwd
/home/vsts/work/1/s
> find . -name testfile.txt
./selenium/tests/flows/testfile.txt

這意味着該文件確實位於/home/vsts/work/1/s/selenium/tests/flows/testfile.txt

我和我的團隊在谷歌上搜索並搜索了為什么會這樣,並找到了@DebanjanB 的答案。

我們沒有意識到的是selenium/standalone-chrome Docker 圖像正在運行 Selenium 網格服務器,它是“遠程”而不是“本地”。 因此驅動程序在運行“遠程”時找不到該文件。

解決方案

我們添加了

driver.setFileDetector(new FileDetector());

await (
  await driver.findElement(By.xpath("//form//input[@id='upload-input']"))
).sendKeys(join(__dirname, "testfile.txt"));

現在,在我們的管道中針對 docker 容器運行時,我們的測試也通過了!

從 Selenium 的文檔中:

本地文件檢測器允許將文件從客戶端機器傳輸到遠程服務器。 例如,如果測試需要將文件上傳到 web 應用程序,遠程 WebDriver 可以在運行時自動將文件從本地機器傳輸到遠程 web 服務器。 這允許從運行測試的遠程機器上載文件。

來源: https://www.selenium.dev/documentation/webdriver/remote_webdriver/#local-file-detector

我希望這會幫助那些在同樣問題上苦苦掙扎的人:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM