【问题标题】:How to check the checkboxes using the Selenium Java WebDriver?如何使用 Selenium Java WebDriver 检查复选框?
【发布时间】:2016-10-29 14:29:35
【问题描述】:

我试图找出一种方法来检查表格网格中的复选框。通常它们被定义为 type='checkbox'。所以我发现很难使用 webDriver 来检查复选框,因为它们在标签中。

下面给出了一个示例 HTML 代码。

<tbody id="gridview-2345-body">
	<tr id="gridview-2345-record-/DNA/Study1_HS.xml" class="x4-grid-row x4-grid-data-row x4-grid-row-selected" data-boundview="gridview-1270" role="row">
		<td id="ext4-ext-gen1234" class="x4-grid-cell x4-grid-td" role="gridcell">
			<div class="x4-grid-cell-inner " style="text-align:left;" unselectable="on">
				<div class="x4-grid-row-checker"/>
			</div>
		</td>
		<td id="ext4-ext-1235" class="x4-grid-cell x4-grid-td" role="gridcell">
			<div class="x4-grid-cell-inner " style="text-align:left;" unselectable="on">
				<span id="ext4-icon1568" class="fa fa-file-code-o labkey-file-icon"/>
			</div>
		</td>
		<td id="ext4-ext-gen1236" class="x4-grid-cell x4-grid-td" role="gridcell">
			<div class="x4-grid-cell-inner " style="text-align:left;" unselectable="on">
				<div width="100%" height="16px">
					<div style="float: left;"/>
					<div style="padding-left: 8px; white-space:normal !important;">
						<span style="display: inline-block; white-space: nowrap;">Study1_HS.xml</span>
					</div>
				</div>
			</div>
		</td>
	</tr>
</tbody>

我尝试在 xpath 中使用“包含”

driver.findElement(By.xpath("//*[contains(@id, 'Study1_HS.xml')]/td[1]/div/div")).click();

【问题讨论】:

  • 它的检查,但我看到其他一些使用 click() 的帖子,所以我尝试使用 click()。一旦我检查了表格行中的复选框。我需要单击另一个按钮。但到目前为止,我只是在尝试一种方法来检查复选框。
  • 您在使用.click()..时是否出现异常或其他问题。
  • @SaurabhGaur - 它给出此消息“错误:无法找到元素:xpath=//*[contains(@id, 'Study1_HS.xml')] 有关此错误的文档,请访问: seleniumhq.org/exceptions/no_such_element.html"
  • 尝试在浏览器控制台中使用 $x("/") 来查找该 xpath 中的错误。该示例 HTML 代码缺少 标记。没有那个标签,chrome 不会渲染你的 tr 标签
  • @shockwave:如果勾选了复选框,能否告诉我HTML代码是否有任何变化?

标签: java html selenium checkbox selenium-webdriver


【解决方案1】:

所以我在 xpath 中使用了“preceding”来使其工作

//span[text()='Study1_HS.xml']/preceding::td/div/div[@class='x4-grid-row-checker']

http://www.xpathtester.com/xpath/b1d50008dd4be8ab7545548c4b8238f5

【讨论】:

    【解决方案2】:

    我想知道...由于选中复选框时 TR 包含类更改,因此单击 TR 可能会触发检查。试试这个看看。

    String searchText = "Study1_HS.xml";
    List<WebElement> rows = driver.findElements(By.tagName("tr"));
    for (WebElement row : rows)
    {
        if (row.getText().contains(searchText))
        {
            row.click();
            break;
        }
    }
    

    【讨论】:

    • 如果这不起作用...右键单击复选框并检查元素。出现了什么元素?
    猜你喜欢
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 2018-04-24
    • 2015-12-23
    • 2023-04-11
    • 2017-06-09
    相关资源
    最近更新 更多