如何解决使用 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()
然而,这给了我一个错误:
无法定位元素
解决方法
第一个问题很好。
如果您需要选择的单选按钮始终是第二个选项,您可以通过索引选择它(以下是在 C# 中,但对于 Python 应该类似):
// get all elements where id = "getAttachmentValue"
var radioButtons = driver.FindElements(By.Id("getAttachmentValue"));
// click second element
radioButtons[1].Click();
编辑(Python):
from selenium.webdriver.common.by import By
radioButtons = driver.find_elements(By.ID,'getAttachmentValue')
radioButtons[1].click()
我将您的 HTML 添加到一个简单的 HTML 文件中,并且能够使用上述示例(使用 C#)选择第二个单选按钮:
,您可以使用数组索引符号通过 xpath 选择第二个单选按钮。不要定位 value
属性,而是使用 name
属性。 name属性的值好像是一致的:
xpath = "(//input[@type = 'radio' and @name = 'getAttachmentValue'])[2]"
radio_button = driver.find_element_by_xpath(xpath)
radio_button.click()
您可能不应该在定位器中使用 id
属性。整个网页的 Id 属性值必须是唯一的,但每个单选按钮的 Id 属性值都是重复的。这是无效的 HTML。最好避免在定位器中使用这些属性的值违反 HTML 规范的属性。你永远不会完全知道浏览器会如何对待它。
对于您的用例,name
属性最有效。具有重复的 name 属性值是完全有效的 HTML,并且 name 属性的值对于每个页面视图似乎都是稳定的。
如果您只有两个相同的 ID,答案很简单。试试这个。
driver.find_element_by_css_selector("#getAttachmentValue:nth-of-type(2)")
如果有更多 - 解决方案可能会更复杂。 怎么会有 ID?