首页 > 解决方案 > 使用 Selenium 选择单选按钮,其值会发生变化

问题描述

我需要选择下面的单选按钮value="QMBT-0029104.xlsx;SYPFJPC2MQHC-5-688478#QHBTW"

HTML:

<form name="ViewQueryForm" method="post" action="/equery/getAttachments.do">

<div class="txt_align_left innerdvcont" id="tabmenu1" style="display:">

<div class="clear"></div>

<div class="txt_align_left innerdvcont" id="tabmenu011" name="tabmenu011">

        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <thead>
             <tr>
            <th width="10%" style="text-align: left"></th>
                    <th width="60%" style="text-align: left">Attachment </th>
                    <th width="30%" style="text-align: left">Date </th>
                    
            </tr>
                </thead>
        
                <tbody>
                <tr>
                <td align="center" valign="top">
                <input type="radio" name="getAttachmentValue" id="getAttachmentValue" value="Dispute_1466718.xlsx;SYPFJPC2MQHC-5-687433#QHBTW"> </td>
                    <td style="padding:5px 4px">Dispute_1466718.xlsx</td>
                    <td style="padding:5px 4px">2021-02-16T10:34:08.617</td>
                    
                        </tr>
                        
                </tbody><tbody>
                <tr>
                <td align="center" valign="top">
                <input type="radio" name="getAttachmentValue" id="getAttachmentValue" value="QMBT-0029104.xlsx;SYPFJPC2MQHC-5-688478#QHBTW">    </td>
                    <td style="padding:5px 4px">QMBT-0029104.xlsx</td>
                    <td style="padding:5px 4px">2021-03-27T08:08:46.09</td>
                    
                        </tr>
                        
                
            </tbody>    
            </table>    
</div>  

到目前为止,我已经能够使用以下代码单击它:

radiobutton2 = driver.find_element_by_xpath("//input[@value='QMBT-0029104.xlsx;SYPFJPC2MQHC-5-688478#QHBTW']");
radiobutton2.click()

但是,该值每次都会更改,这意味着它不是我在运行代码时可以使用的东西。例如,有什么方法可以默认选择第二个单选按钮。或者,我会知道QMBT-00000参考,那么有没有办法通过搜索该文本来选择单选按钮?

我努力了:

radiobutton2 = driver.find_element_by_xpath('//*[contains(text(), "QMBT-0029104") and @id="getAttachmentValue"]');
radiobutton2.click()

但是,这给了我一个错误:

无法定位元素

标签: pythoncssseleniumselenium-webdriverelement

解决方案


如果你只有两个相同的 id,答案很简单。尝试这个。

driver.find_element_by_css_selector("#getAttachmentValue:nth-of-type(2)")

如果有更多 - 解决方案可能会更复杂。ID 怎么可能存在?


推荐阅读