繁体   English   中英

使用 Selenium + Python 无法单击 label 元素

[英]Unable to click label element using Selenium + Python

我有这行代码,我想使用 Selenium WebDriver 和 Python 单击它,它源自 iframe:

<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>

我想单击“选择文件”label(它是一个按钮,但没有 XPath 或 id)但我真的无法这样做......

这是 iframe:

<iframe id="upload_iframe" allowtransparency="true" class="  " role="presentation" tabindex="0" src="http://www.test.com/webclient/utility/uploadfile.jsp?controlId=itemimage_3_1&amp;componentId=itemimage_3_1-if&amp;uisessionid=1689" scrolling="no" marginheight="0" marginwidth="0" onfocus="setCurrentfocusId(event,this);" style="border:0px;" width="400" height="33" frameborder="0"> </iframe>

我已经使用这行脚本单击 label 但按钮不响应我的代码:

button_element = browser.find_element_by_class_name('pb default')
button_element.click()

你知道如何点击那个元素吗? 我正在使用 firefox 来做到这一点......感谢任何答案,谢谢。

尝试在单击操作之前使用显式等待:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it(
    (By.ID, "upload_iframe")))
browser.switch_to.frame(browser.find_element_by_id("upload_iframe"))
WebDriverWait(browser, 20).until(EC.element_to_be_clickable(
    (By.CSS_SELECTOR, ".pb.default"))).click()

要切换回原始内容,请使用以下命令:

browser.switch_to.default_content()    

我希望它对你有帮助!

使用标签的内部文本获取元素,

driver.findElement(By.xpath("//label[contains(text(),'Select File')]")).click()

要访问 iframe,您必须使用.switchTo().frame切换到它。 见下文。 我注释掉了 switch back 命令。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


WebDriverWait(browser, 10).until(EC.presence_of_element_located(
    (By.ID, ".pb.upload_iframe")))

browser.switchTo().frame("upload_iframe")

WebDriverWait(browser, 10).until(EC.element_to_be_clickable(
    (By.CSS_SELECTOR, ".pb.default"))).click()


#browser.switchTo().defaultContent()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM