簡體   English   中英

如何使用 Selenium 和 Python 單擊元素

[英]How to click an element using Selenium and Python

我在使用 selenium 中的 XPath 單擊元素時遇到問題。 這是問題的 HTML 元素:

<label for="file" class="pb default" style="display: inline-block;margin: 5px 10px;">Select File</label>

你知道這個的解決方案嗎? 任何回應都非常感謝。

更新:

這是問題的完整源代碼

<html>
<head>
    <META http-equiv="Content-Type" content="text/html; charset=utf-8">
    <BASE HREF="http://1.1.1.19/webclient/utility">
    <link rel=stylesheet type="text/css" href="../webclient/skins/skins-20190807-1904/iot18/css/filex.css">
</head>
<body style="background: transparent; background-color: transparent">
<form name="IMPORT" id="IMPORT" enctype="multipart/form-data" method="post">
    <input type="hidden" NAME="componetId" VALUE="itemimage_3_1-if">
    <input type="hidden" NAME="controlId" VALUE="itemimage_3_1">
    <table width="100%" cellspacing="0" align="center" class="maintable">
        <tr>

            <td align="left"  style="white-space: nowrap;">

                    <label for="file" class="pb default" style="display: inline-block;margin: 5px 10px;">Select File</label>
                    <input id="fileName" onmousedown="" type="text" value="" class="fld fld_ro text ib" readonly size="50"/> 
                
                <input id="file" type="file" name="value" title="Specify a New File" onchange="" size="35" class="text"  style="    width: 0.1px;height: 0.1px !important;fileStyle: 0;overflow: hidden;position: absolute;z-index: -1;opacity: 0;" value="" onclick="if(!parent.undef(parent.firingControl) && parent.firingControl.id==this.id){parent.sendEvent('clientonly','clickFileButton', this.id)}">

            </td>
        </tr>
    </table>
</form>
</body>
<script>
    document.querySelector('#file').addEventListener('change', function(e){
        document.querySelector('#fileName').value = e.currentTarget.files[0].name;
    });
</script>

</html>

可以嘗試使用//label[@for='file']//label[@for='file'][text()='Select File']

如果這不起作用,則可能是您定位了錯誤的元素,或者您在它出現之前等待的時間不夠長。 在處理上傳文件時,我使用類型文件 //input[@type='file'] 來定位輸入,而不是 label,您可能需要提供更大的 HTML 部分。

如果class=pb default是網頁中唯一的 class 則試試這個。

driver.driver.find_element(By.XPATH,'//*[@class="pb default"]').click()

或者您可以通過文本搜索Select 文件

driver.find_element(By.XPATH,'//*[contains(text(),"Select File")]').click()

好吧,,您不要單擊<label>元素。 但是,您可能需要為其他目的定位<label>元素。


要識別<label>元素,您可以使用以下任一Locator Strategies

  • 使用css_selector

     element = driver.find_element(By.CSS_SELECTOR, "label.pb.default[for='file']")
  • 使用xpath

     element = driver.find_element(By.XPATH, "//label[@class='pb default' and text()='Select File']")

暫無
暫無

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

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