java - 上传文档并显示文档状态 - Selenium WebDriver - Java

标签 java selenium selenium-webdriver

@Florent B. 回答了我关于上传元素不是输入类型的文档的问题 type="file"here

现在,我有另一个无法正确处理的文档上传部分。屏幕上有一个带有 input type="submit"按钮的叠加层,所以我使用上面超链接中的解决方案,它确实上传了文档,但是,它不会改变显示文档已上传的状态,这是必需的真正完成订单。

这是我当前上传文档的代码,它只是没有在对话框中反射(reflect)出来:

// disable the click event on an `<input>` file
((JavascriptExecutor)getDriver()).executeScript(
    "HTMLInputElement.prototype.click = function() {                     " +
    "  if(this.type !== 'file') HTMLElement.prototype.click.call(this);  " +
    "};                                                                  " );

// trigger the upload
VOrderDetails.uploadReport_btn(getDriver()).click();

// change the visibility of the file input control
WebElement elem = getDriver().findElement(By.id("UploadLib_Uploader_js"));
String js = "arguments[0].style.height='auto'; arguments[0].style.visibility='visible';";
((JavascriptExecutor) getDriver()).executeScript(js, elem);

Thread.sleep(1000);

getDriver().findElement(By.cssSelector("input[type=file]"))
      .sendKeys(filePath);

File is not showing uploaded

当您手动上传文档时,该文档将显示如下,显示已上传测试 PDF.pdf 文件并允许您完成订单:

enter image description here

有没有办法“伪造”它以显示文档已上传到此叠加层上?

这是这件作品的 HTML:

<div id="divSetComplete" style="width: 594px; display: block; top: 316.5px;" class="MessageBox HideOldProgressBar">
  <div class="DialogTitle">Complete assignment</div>
  <div id="divSetCompleteFields" class="DialogSection dsBorder dsColor">
    <img src="/Images/BlackOne.png" class="dsNumber" alt="">
    <div class="dsCaption">
      <span style="margin-right:2px">Upload the report for <span id="Dialogs_Dialogs_spnOrderAddress" class="VariableText">245 W Chantilly Way</span> to your client, <span id="Dialogs_Dialogs_spnOrderClient" class="VariableText">Automation Test User</span>.</span>
    </div>
    <div class="dsContent UploadFields">



      <div id="Dialogs_Dialogs_divFile">
        <div>
          <div id="divProgressBarFile" class="ProgressBarDiv">
            <div id="pbFile" style="display: inline-block; position: relative;">
              <div id="pbFile_divEmpty" class="EmptyGradient BasicStyling" style="width: 371px; display: inline-block; height: 24px; line-height: 24px;">
                <div id="pbFile_divProgress" class="ProgressGradient" style="height: 22px;">
                  <div class="ProgressBackground BasicStyling" style="width: 371px; height: 22px; line-height: 24px;">
                    <label id="pbFile_ProgressText" class="ProgressText" style="width: 319px; height: 24px;"></label><i id="pbFile_ProgressIcon" onclick="ProgressBar.CancelUpload('pbFile','pbFile_Icon','Dialogs_Dialogs_uplFile',true,'Required');" class="fa fa-times ProgressIcon" style="left: 344px; line-height: 24px;"></i>
                  </div>
                </div>
                <label class="EmptyText PlaceholderText" id="pbFile_EmptyText" style="width: 319px; height: 24px; line-height: 20px;">Required</label><i id="pbFile_Icon" class="fa fa-times EmptyIcon" onclick="ProgressBar.CancelUpload('pbFile','pbFile_Icon','Dialogs_Dialogs_uplFile',true,'Required');" style="line-height: 24px; display: none;"></i>
              </div>
            </div>
          </div>
          <div class="SkinButtonDiv">
            <input type="submit" name="ctl00$ctl00$Dialogs$Dialogs$btnUploadFile" value="Upload report" onclick="HideDialog();" id="Dialogs_Dialogs_btnUploadFile" class="MercuryButton Blue" style="height:24px;width:141px;">
          </div>
        </div>
      </div>
    </div>
  </div>
  <div id="divSetCompleteMessage" class="DialogSection dsBorder dsColor">
    <span id="Dialogs_Dialogs_upSetComplete">
                    <img src="/Images/BlackTwo.png" class="dsNumber" alt="">
                    <div class="dsContent">

                        <div>


<div id="Dialogs_Dialogs_ctlCompleteMessage_divNormal">
    <div class="MercuryField">
        <div class="smFieldLabel">Message to client</div>
    </div>
    <div class="MercuryField">
        <div class="MercuryFieldInput">
            <textarea name="ctl00$ctl00$Dialogs$Dialogs$ctlCompleteMessage$txtMessage" rows="2" cols="20" id="Dialogs_Dialogs_ctlCompleteMessage_txtMessage" class="MercuryInput smNormalComment"></textarea>
            <div id="Dialogs_Dialogs_ctlCompleteMessage_hbStatusMessage_pnlHoverWrapper" class="hoverPopupMenu" style="background-color: white; position: absolute; visibility: hidden; left: 517px; top: 29px; z-index: 1000; display: none;">
    <img src="/Images/QuickListImages/QL.png" id="Dialogs_Dialogs_ctlCompleteMessage_hbStatusMessage_btnHover" class="hoverImageBtn" onclick="MercuryNetwork.Common.Controls.QuickList.HoverButton.onClientClick(this, event);" data-client-event="Event_HoverButton_Click" data-target-control-i-d="txtMessage" data-target-control-client-i-d="Dialogs_Dialogs_ctlCompleteMessage_txtMessage" data-user-data="">
</div>
        </div>
    </div>
</div>
                        </div>
                    </div>
                    <div style="display:none">
                                <input id="Dialogs_Dialogs_uplEnv" name="ctl00$ctl00$Dialogs$Dialogs$uplEnv" type="hidden" autocomplete="off" isuploaderfield="1"><button>Upload&nbsp;a&nbsp;file</button><img uniqueid="ctl00$ctl00$Dialogs$Dialogs$uplEnv" namespace="CuteWebUI" root="/" verticks="635229096420000000" filetoolargemsg="{0} cannot be uploaded!

File size ({1}) is too large. The maximum file size allowed is set to: {2}." windowsdialoglimitmsg="Unable to select so many files at once. The total file name length cannot exceed 32kb." canceluploadmsg="Cancel upload" cancelallmsg="Cancel all Uploads" uploadingmsg="Uploading.." uploadaddonbuttonmode="Auto" advancedoptionnosilverlight="true" uploadtype="Auto" uploadcursor="Auto" uploadtypepriority="Silverlight,HTML5,Flash,IFrame" maxfileslimit="1" uploadedfilecount="0" showprogressinfo="1" progresstexttemplate="%SEND% of %SIZE%; %T% seconds left" panelwidth="360" barheight="20" infostyle="padding-left:3px;font:normal 12px Tahoma;" barstyle="Continuous" borderstyle="border:1px solid #444444;" postbackeventreference="__doPostBack('ctl00$ctl00$Dialogs$Dialogs$uplEnv','')" insertbuttonid="Dialogs_Dialogs_btnUploadEnv" cancelbuttonid="Dialogs_Dialogs_uplEnv__Cancel" progresstextid="Dialogs_Dialogs_uplEnv__ProgressText" progressctrlid="Dialogs_Dialogs_uplEnv__Progress" maxsizekb="51200" extensions="env" inserttext="Upload a file" inputboxcsstext="" contextvalue="!3wEWAQVQXFxzczEuaW50ZXJuYWwuYWQubWVyY3VyeXZtcC5jb21cU2hhcmVkIFN0b3JhZ2VcbWVyY3VyeS5hbGFtb2RlLmNvbVxVcGxvYWRlclRlbXBqJn5!30YJ9bQs4t7i2cbnRNiNu2w!2!2" serverlang="AspNet" id="Dialogs_Dialogs_uplEnvImage_unique" resourcehandler="/CuteWebUI_Uploader_Resource.axd" onload="this.style.display=&quot;none&quot; ; if(!window.CuteWebUI_AjaxUploader_Initialize){var xh=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHttp');xh.open('GET','/CuteWebUI_Uploader_Resource.axd?type=script&amp;_ver=635229096420000000',false);xh.send('');eval(xh.responseText)}CuteWebUI_AjaxUploader_Initialize(this.id);" onerror="this.onload()" src="/CuteWebUI_Uploader_Resource.axd?type=file&amp;file=continuous.gif" style="display:none;"><div id="Dialogs_Dialogs_uplEnv__Progress" style="display:none;">
    <span id="Dialogs_Dialogs_uplEnv__ProgressText" style="display: none;">Uploading...</span>
    <input type="submit" name="ctl00$ctl00$Dialogs$Dialogs$uplEnv$_Cancel" value="Cancel" id="Dialogs_Dialogs_uplEnv__Cancel" style="display: none;">
  </div>
  <input id="Dialogs_Dialogs_uplMismo" name="ctl00$ctl00$Dialogs$Dialogs$uplMismo" type="hidden" autocomplete="off" isuploaderfield="1">
  <button>Upload&nbsp;a&nbsp;file</button>
  <img uniqueid="ctl00$ctl00$Dialogs$Dialogs$uplMismo" namespace="CuteWebUI" root="/" verticks="635229096420000000" filetoolargemsg="{0} cannot be uploaded!

File size ({1}) is too large. The maximum file size allowed is set to: {2}." windowsdialoglimitmsg="Unable to select so many files at once. The total file name length cannot exceed 32kb." canceluploadmsg="Cancel upload" cancelallmsg="Cancel all Uploads"
  uploadingmsg="Uploading.." uploadaddonbuttonmode="Auto" advancedoptionnosilverlight="true" uploadtype="Auto" uploadcursor="Auto" uploadtypepriority="Silverlight,HTML5,Flash,IFrame" maxfileslimit="1" uploadedfilecount="0" showprogressinfo="1" progresstexttemplate="%SEND% of %SIZE%; %T% seconds left"
  panelwidth="360" barheight="20" infostyle="padding-left:3px;font:normal 12px Tahoma;" barstyle="Continuous" borderstyle="border:1px solid #444444;" postbackeventreference="__doPostBack('ctl00$ctl00$Dialogs$Dialogs$uplMismo','')" insertbuttonid="Dialogs_Dialogs_btnUploadMismo"
  cancelbuttonid="Dialogs_Dialogs_uplMismo__Cancel" progresstextid="Dialogs_Dialogs_uplMismo__ProgressText" progressctrlid="Dialogs_Dialogs_uplMismo__Progress" maxsizekb="51200" extensions="xml" inserttext="Upload a file" inputboxcsstext="" contextvalue="!3wEWAQVQXFxzczEuaW50ZXJuYWwuYWQubWVyY3VyeXZtcC5jb21cU2hhcmVkIFN0b3JhZ2VcbWVyY3VyeS5hbGFtb2RlLmNvbVxVcGxvYWRlclRlbXBqJn5!30YJ9bQs4t7i2cbnRNiNu2w!2!2"
  serverlang="AspNet" id="Dialogs_Dialogs_uplMismoImage_unique" resourcehandler="/CuteWebUI_Uploader_Resource.axd" onload="this.style.display=&quot;none&quot; ; if(!window.CuteWebUI_AjaxUploader_Initialize){var xh=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHttp');xh.open('GET','/CuteWebUI_Uploader_Resource.axd?type=script&amp;_ver=635229096420000000',false);xh.send('');eval(xh.responseText)}CuteWebUI_AjaxUploader_Initialize(this.id);"
  onerror="this.onload()" src="/CuteWebUI_Uploader_Resource.axd?type=file&amp;file=continuous.gif" style="display:none;">
  <div id="Dialogs_Dialogs_uplMismo__Progress" style="display:none;">
    <span id="Dialogs_Dialogs_uplMismo__ProgressText" style="display: none;">Uploading...</span>
    <input type="submit" name="ctl00$ctl00$Dialogs$Dialogs$uplMismo$_Cancel" value="Cancel" id="Dialogs_Dialogs_uplMismo__Cancel" style="display: none;">
  </div>
  <input id="Dialogs_Dialogs_uplPdf" name="ctl00$ctl00$Dialogs$Dialogs$uplPdf" type="hidden" autocomplete="off" isuploaderfield="1">
  <button>Upload&nbsp;a&nbsp;file</button>
  <img uniqueid="ctl00$ctl00$Dialogs$Dialogs$uplPdf" namespace="CuteWebUI" root="/" verticks="635229096420000000" filetoolargemsg="{0} cannot be uploaded!

File size ({1}) is too large. The maximum file size allowed is set to: {2}." windowsdialoglimitmsg="Unable to select so many files at once. The total file name length cannot exceed 32kb." canceluploadmsg="Cancel upload" cancelallmsg="Cancel all Uploads"
  uploadingmsg="Uploading.." uploadaddonbuttonmode="Auto" advancedoptionnosilverlight="true" uploadtype="Auto" uploadcursor="Auto" uploadtypepriority="Silverlight,HTML5,Flash,IFrame" maxfileslimit="1" uploadedfilecount="0" showprogressinfo="1" progresstexttemplate="%SEND% of %SIZE%; %T% seconds left"
  panelwidth="360" barheight="20" infostyle="padding-left:3px;font:normal 12px Tahoma;" barstyle="Continuous" borderstyle="border:1px solid #444444;" postbackeventreference="__doPostBack('ctl00$ctl00$Dialogs$Dialogs$uplPdf','')" insertbuttonid="Dialogs_Dialogs_btnUploadPdf"
  cancelbuttonid="Dialogs_Dialogs_uplPdf__Cancel" progresstextid="Dialogs_Dialogs_uplPdf__ProgressText" progressctrlid="Dialogs_Dialogs_uplPdf__Progress" maxsizekb="51200" extensions="pdf" inserttext="Upload a file" inputboxcsstext="" contextvalue="!3wEWAQVQXFxzczEuaW50ZXJuYWwuYWQubWVyY3VyeXZtcC5jb21cU2hhcmVkIFN0b3JhZ2VcbWVyY3VyeS5hbGFtb2RlLmNvbVxVcGxvYWRlclRlbXBqJn5!30YJ9bQs4t7i2cbnRNiNu2w!2!2"
  serverlang="AspNet" id="Dialogs_Dialogs_uplPdfImage_unique" resourcehandler="/CuteWebUI_Uploader_Resource.axd" onload="this.style.display=&quot;none&quot; ; if(!window.CuteWebUI_AjaxUploader_Initialize){var xh=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHttp');xh.open('GET','/CuteWebUI_Uploader_Resource.axd?type=script&amp;_ver=635229096420000000',false);xh.send('');eval(xh.responseText)}CuteWebUI_AjaxUploader_Initialize(this.id);"
  onerror="this.onload()" src="/CuteWebUI_Uploader_Resource.axd?type=file&amp;file=continuous.gif" style="display:none;">
  <div id="Dialogs_Dialogs_uplPdf__Progress" style="display:none;">
    <span id="Dialogs_Dialogs_uplPdf__ProgressText" style="display: none;">Uploading...</span>
    <input type="submit" name="ctl00$ctl00$Dialogs$Dialogs$uplPdf$_Cancel" value="Cancel" id="Dialogs_Dialogs_uplPdf__Cancel" style="display: none;">
  </div>
  <input id="Dialogs_Dialogs_uplFile" name="ctl00$ctl00$Dialogs$Dialogs$uplFile" type="hidden" autocomplete="off" isuploaderfield="1">
  <img uniqueid="ctl00$ctl00$Dialogs$Dialogs$uplFile" namespace="CuteWebUI" root="/" verticks="635229096420000000" filetoolargemsg="{0} cannot be uploaded!

File size ({1}) is too large. The maximum file size allowed is set to: {2}." windowsdialoglimitmsg="Unable to select so many files at once. The total file name length cannot exceed 32kb." canceluploadmsg="Cancel upload" cancelallmsg="Cancel all Uploads"
  uploadingmsg="Uploading.." uploadaddonbuttonmode="Auto" advancedoptionnosilverlight="true" uploadtype="Auto" uploadcursor="Auto" uploadtypepriority="Silverlight,HTML5,Flash,IFrame" maxfileslimit="1" uploadedfilecount="0" showprogressinfo="1" progresstexttemplate="%SEND% of %SIZE%; %T% seconds left"
  panelwidth="360" barheight="20" infostyle="padding-left:3px;font:normal 12px Tahoma;" barstyle="Continuous" borderstyle="border:1px solid #444444;" postbackeventreference="__doPostBack('ctl00$ctl00$Dialogs$Dialogs$uplFile','')" insertbuttonid="Dialogs_Dialogs_btnUploadFile"
  cancelbuttonid="Dialogs_Dialogs_uplFile__Cancel" progresstextid="Dialogs_Dialogs_uplFile__ProgressText" progressctrlid="Dialogs_Dialogs_uplFile__Progress" maxsizekb="51200" extensions="pdf,xml" inserttext="Upload a file" inputboxcsstext="" contextvalue="!3wEWAQVQXFxzczEuaW50ZXJuYWwuYWQubWVyY3VyeXZtcC5jb21cU2hhcmVkIFN0b3JhZ2VcbWVyY3VyeS5hbGFtb2RlLmNvbVxVcGxvYWRlclRlbXBqJn5!30YJ9bQs4t7i2cbnRNiNu2w!2!2"
  serverlang="AspNet" id="Dialogs_Dialogs_uplFileImage_unique" resourcehandler="/CuteWebUI_Uploader_Resource.axd" onload="this.style.display=&quot;none&quot; ; if(!window.CuteWebUI_AjaxUploader_Initialize){var xh=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHttp');xh.open('GET','/CuteWebUI_Uploader_Resource.axd?type=script&amp;_ver=635229096420000000',false);xh.send('');eval(xh.responseText)}CuteWebUI_AjaxUploader_Initialize(this.id);"
  onerror="this.onload()" src="/CuteWebUI_Uploader_Resource.axd?type=file&amp;file=continuous.gif" style="display:none;">
  <div id="Dialogs_Dialogs_uplFile__Progress" style="display:none;">
    <span id="Dialogs_Dialogs_uplFile__ProgressText" style="display: none;">Uploading...</span>
    <input type="submit" name="ctl00$ctl00$Dialogs$Dialogs$uplFile$_Cancel" value="Cancel" id="Dialogs_Dialogs_uplFile__Cancel" style="display: none;">
  </div>
</div>
</span>
</div>
<div class="DialogFooter">
  <div class="MessageBoxButton">
    <a id="Dialogs_Dialogs_btnSetCompleteCancel" onclick="return ButtonVerifyEnabled(this, ResetComplete(true));" class="SkinButton sbGray" onmouseover="ButtonHover(this,30);" onmouseout="ButtonLeave(this);" onmousedown="ButtonDown(this,30);" onmouseup="ButtonHover(this,30);"
    skinheight="30" style="color:Black;width:72px;height:30px;line-height:30px;">
      <div class="SkinButtonLeft"></div>
      <div class="SkinButtonRight"></div>Cancel</a>
  </div>
  <div class="MessageBoxButton">
    <a id="Dialogs_Dialogs_btnSetCompleteOK" onclick="return ButtonVerifyEnabled(this, SetStatusComplete());" class="SkinButton sbBlue" onmouseover="ButtonHover(this,30);" onmouseout="ButtonLeave(this);" onmousedown="ButtonDown(this,30);" onmouseup="ButtonHover(this,30);"
    skinheight="30" style="color:White;width:72px;height:30px;line-height:30px;">
      <div class="SkinButtonLeft"></div>
      <div class="SkinButtonRight"></div>OK</a>
  </div>
</div>
</div>

这是文件上传后的HTML:

<div id="pbFile_divEmpty" class="EmptyGradient BasicStyling" style="width: 371px; display: inline-block; height: 24px; line-height: 24px;">
  <div id="pbFile_divProgress" class="ProgressGradient" style="height: 22px; width: 100%;">
    <div class="ProgressBackground BasicStyling" style="width: 371px; height: 22px; line-height: 24px;">
      <label id="pbFile_ProgressText" class="ProgressText" style="width: 319px; height: 24px;">Test PDF.pdf</label><i id="pbFile_ProgressIcon" onclick="ProgressBar.CancelUpload('pbFile','pbFile_Icon','Dialogs_Dialogs_uplFile',true,'Required');" class="fa fa-times ProgressIcon" style="left: 344px; line-height: 24px;"></i>
    </div>
  </div>
  <label class="EmptyText " id="pbFile_EmptyText" style="width: 319px; height: 24px; line-height: 20px;">Test PDF.pdf</label><i id="pbFile_Icon" class="fa fa-times EmptyIcon" onclick="ProgressBar.CancelUpload('pbFile','pbFile_Icon','Dialogs_Dialogs_uplFile',true,'Required');" style="line-height: 24px; display: inline-block;"></i>
</div>

我在上传文件时点击了上传按钮,就可以截取下面的屏幕截图。

enter image description here

最佳答案

安装 Autoit 并尝试以下操作。

How to install autoit , 您可以使用此链接安装。

安装后。然后执行以下操作:

开始菜单 -> 所有程序 -> AutoIt V3 -> SciTE Script Editor

enter image description here

复制并粘贴到那里:这是给火狐的

ControlFocus("File Upload","","Edit")
Sleep(2000)
send("test.txt")
Sleep(2000)
send("{ENTER}")

enter image description here

编译它:

工具 -> 编译或 Cntr+F7

从 .au3 文件创建 .exe 文件:

开始 -> 所有程序 -> AutoIt v3 -> 将脚本编译为 .exe

enter image description here

一旦你运行这个 .exe 文件将在 .au3 文件所在的文件夹下创建。你需要在你的测试代码中引用这个文件。

我的html文件

    <html>
<body>
<script>
function uploadOnChange(e) {
    var filename = e.value;var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex +1);
    }
    document.getElementById('filename').value = filename;
}
</script>
<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />


</body>
</html>

我的测试代码:

    import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class FileUploadTest {

    private static WebDriver driver = null;

    @Test
    public void testFileUpload() throws IOException, InterruptedException, IOException {

        driver = new FirefoxDriver();

        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.get("file:///C:/Users/sv/Desktop/uploadDoc.html");

        driver.findElement(By.id("upload")).click();

        Runtime.getRuntime().exec("<exe file path>");

        Thread.sleep(6000);

        System.out.println(driver.findElement(By.id("filename")).getText());

        driver.close();

    }
}

更多信息,请引用 link

关于java - 上传文档并显示文档状态 - Selenium WebDriver - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40086692/

相关文章:

java - 设置 JavaFX FileChooser 的初始目录

java - Intellij IDEA 快捷方式 如何添加新元素(例如类或包)?

java - 内存缓存错误 : Broken pipe/Connection reset by peer

selenium - Web 应用程序和移动应用程序自动化测试以及 selenium/appium

c# - 使用 Selenium 使用 WindowHandles 跟踪和迭代选项卡和窗口的最佳方法

java - 使用 gson 解析 JSON 数组

java - 无法使用 Java selenium 单击 JSP 网页框架内的元素

java - 使用 selenium 实现两个类到第三个类的功能的架构

ios - 使用Appium生成 Protractor 脚本时,有没有具体的元素定位方式?

scala - 为 Play 项目并行运行 Selenium 测试