当 style="display:none;" 时,Selenium 上传文件

Selenium Upload File when style="display:none;"

我收到错误消息“无法通过键盘访问元素”,请大家帮帮我。我只想附上 PDF 文件,但随着鼠标的移动,我找不到点击它的地方,也找不到上传文件。

代码是:-

WebElement uploadElement = driver.findElement(By.xpath("//*[@id=\"registerproduct\"]/div/div[4]/div/div/div/div[2]/div[2]/div/div/span/label"));
uploadElement.sendKeys("C:\Users\Rahul\Downloads\kemgo-auction-detail-574.pdf");

Html是:-

<div class="col s12">
 <div class="file-field input-field">
    <div class="">
         <input id="btn_myFileInput" onchange="checkimagetype()" name="productsheet" style="display:none;" type="file">
         <span class="attached sp_head">
          <label for="btn_myFileInput" class="gray-lite attach_circle left"> 
              <i class="fa fa-paperclip small"></i>
           </label>
         <span class="sp_head">
        Attach specification sheet                                            </span>
          <span id="fileinput-msg"></span> </span>

    </div>
 </div> 

你们能帮我上传文件吗? 谢谢

根据您分享的HTML和您的代码试验 WebElement传递文件路径不是<label>标签。您应该定位 <input> 标签。此外,<input> 标签将 style 属性设置为 display: none;。您可以使用以下代码块上传文件:

WebElement uploadElement = driver.findElement(By.xpath("//input[@id='btn_myFileInput']"));
((JavascriptExecutor)driver).executeScript("arguments[0].removeAttribute('style')", uploadElement);
uploadElement.sendKeys("C:\Users\Rahul\Downloads\kemgo-auction-detail-574.pdf");

这是我的解决方案,我认为它可以解决其他情况。我会解释清楚我的代码

    driver.executeScript("return document.readyState").equals("complete");

    WebElement uploadImage = driver.findElementByXPath("*<your_xPath_element>*");

    String scriptOn = "arguments[0].setAttribute('style','display: block')";

    driver.executeScript(scriptOn, uploadImage);

    uploadImage.sendKeys("*<your_image_URL>*");

    String scriptOff = "arguments[0].setAttribute('style','display: none')";

    driver.executeScript(scriptOff, uploadImage);

解释:

前置条件:

驱动程序:FFDriver

语言:Java

步骤:

第 1 行:因为它是一个隐藏元素,所以您不知道它何时出现 => 这就是为什么您需要等待页面完全加载

第2行:定义你要检测的元素,不用担心它检测不到 例如我的 xPath://input[@accept='image/']*

第 3 行:按照您的预期为 Style 属性定义新值 例如 URL = "path/01.png"

第 4 行:执行命令元素的当前样式 = 新值 ('style','display: block') => 它使隐藏元素显示

第 5 行:现在您的期望元素已显示,因此您可以向其发送密钥(图片 URL)

第 6 + 7 行:return此元素的原始状态

style="display:none;"

时,使用元素 ID 使输入字段可见
 public void makeInputElementVisible(){
     JavascriptExecutor executor = (JavascriptExecutor)driver;
     executor.executeScript("document.getElementById('your_element_id').style.display='block';");
    }

style="display:none;"

时,使用 css 选择器使输入字段可见
 public void makeInputElementVisible(){
     JavascriptExecutor executor = (JavascriptExecutor)driver;
     executor.executeScript("document.querySelector('your_css_selector_for_input_field').style.display='block';");
    }