Webdriver 通过输入查找元素 class returns "no such element"

Webdriver findElement by input class returns "no such element"

我想用 Webdriver 在 table 中写点东西。所以,基本上我有一个包含 X 行和 Y 列的 table。每个字段都标有例如中的第 0 列第 2 行。

代码如下所示

<!-- language: lang-html -->
<div id="ScheduleTable-01" class="widget Scheduletable suppress-errors Schedule-grid" data-widget="ScheduleTable">
<div class="grid-wrapper">
<table class="nostyles weekmode hourstype fullmonth" style="width: 100%;">
<thead>
<tbody>
<tr id="1165051795" class="Schedule-row row0 1165051795 key_AuthoriserId-1132_JobId-A00890131S_TaskId-OPT1_TsCode-01" data-row-index="0" data-job="EAST BUILDINGS">
<td class="Schedule-col details">
<td class="Schedule-col timeslots">
<div class="timeslots-container" style="opacity: 1; visibility: visible;">
<div class="timeslot d1424343600000 row0 col0 current" data-time="1424343600000" style="width: 3.22581%;">
<div class="timeslot d1424430000000 row0 col1 current" data-time="1424430000000" style="width: 3.22581%;">
<input class="row0 col1 widget class changed color black hi" type="text" autocomplete="off">
</div>
<div class="timeslot d1424516400000 row0 col2 current" data-time="1424516400000" style="width: 3.22581%;">
<input class="row0 col2 widget" type="text" autocomplete="off">
</div>
<div class="timeslot d1424602800000 row0 col3 current" data-time="1424602800000" style="width: 3.22581%;">
<div class="timeslot d1424689200000 row0 col4 current" data-time="1424689200000" style="width: 3.22581%;">
<div class="timeslot d1424775600000 row0 col5 current" data-time="1424775600000" style="width: 3.22581%;">

我想在 table 行 0 列 1 中写“1.1”,所以这个 HTML 部分就是我想要的

<!-- language: lang-html -->
<div class="timeslot d1424516400000 row0 col2 current" data-time="1424516400000" style="width: 3.22581%;">
<input class="row0 col2 widget" type="text" autocomplete="off">
</div>

我的 Selenium 代码如下所示

<!-- language: lang-java -->
WebElement writeSomething = driver.findElement(By.className("row0.col1.widget"));
            writeSomething.sendKeys("1.1");

硒说 org.openqa.selenium.NoSuchElementException: no such element

但如果我使用 xpath,它工作正常

<!-- language: lang-java -->
WebElement writeSomething = driver.findElement(By.xpath(".//*[@id='1165051795']/td[2]/div/div[2]/input"));
writeSomething.sendKeys("1.1");

如何正确地通过类名查找元素? 谢谢。

问题是 - 您正在使用 By.className(),但在内部提供了 CSS 选择器 。相反,使用 By.cssSelector():

WebElement writeSomething = driver.findElement(By.cssSelector("input.row0.col1.widget"));