gpt4 book ai didi

java - 我如何在表单 selenium 上上传文件

转载 作者:行者123 更新时间:2023-12-01 19:40:40 24 4
gpt4 key购买 nike

    <form method="post" enctype="multipart/form-data" class="box dropzone dz-clickable" action="/upload" id="drop">
<div class="disable-click" style="display: none;">
<a class="cross" href="javascript:void(0)">
<img style="cursor:pointer;" src="http://demopayrollplus.finpay.pk/public/assets/images/cross-icon.png" alt="Remove File" title="Remove File"></a>
</div>
<div class="box__input dz-message">
<img id="uploadIcon" src="http://demopayrollplus.finpay.pk/public/assets/images/upload-icon.svg">
<label class="uploadedFileName">Drop your file here</label>
</div>
</form>

我尝试过以下方法

  1. 网络元素。
  2. 行动
  3. 发送 key

但没有任何作用,它说不是棘手的元素

WebElement ele = driver.findElement(By.id("drop"));
ele.sendkeys("file path");

最佳答案

对于拖放文件上传类型,您可以使用下面提到的代码。此代码将从您提到的位置拖动文件并将其放到文件上传位置。

ChromeDriver driver = new ChromeDriver();

driver.get("URL");

// locate the drop area
WebElement droparea = driver.findElement("file upload element");
Point point = droparea.getLocation();
int xcord = point.getX();
int ycord = point.getY();
// drop the file
DropFile(new File("location of file to be uploaded"), droparea, xcord ,ycord);


public static void DropFile(File filePath, WebElement target, int offsetX, int offsetY) {
if(!filePath.exists())
throw new WebDriverException("File not found: " + filePath.toString());

WebDriver driver = ((RemoteWebElement)target).getWrappedDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
WebDriverWait wait = new WebDriverWait(driver, 30);

String JS_DROP_FILE =
"var target = arguments[0]," +
" offsetX = arguments[1]," +
" offsetY = arguments[2]," +
" document = target.ownerDocument || document," +
" window = document.defaultView || window;" +
"" +
"var input = document.createElement('INPUT');" +
"input.type = 'file';" +
"input.style.display = 'none';" +
"input.onchange = function () {" +
" var rect = target.getBoundingClientRect()," +
" x = rect.left + (offsetX || (rect.width >> 1))," +
" y = rect.top + (offsetY || (rect.height >> 1))," +
" dataTransfer = { files: this.files };" +
"" +
" ['dragenter', 'dragover', 'drop'].forEach(function (name) {" +
" var evt = document.createEvent('MouseEvent');" +
" evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);" +
" evt.dataTransfer = dataTransfer;" +
" target.dispatchEvent(evt);" +
" });" +
"" +
" setTimeout(function () { document.body.removeChild(input); }, 25);" +
"};" +
"document.body.appendChild(input);" +
"return input;";

WebElement input = (WebElement)jse.executeScript(JS_DROP_FILE, target, offsetX, offsetY);
input.sendKeys(filePath.getAbsoluteFile().toString());
wait.until(ExpectedConditions.stalenessOf(input));
}

关于java - 我如何在表单 selenium 上上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55487811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com