输入类的Webdriver findElement返回“没有这样的元素”

时间:2015-03-19 04:53:56

标签: java selenium webdriver classname

我想使用Webdriver在表中写一些东西。所以,基本上我有一个X行和Y列的表。每个字段都标有例如第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%;">

我想写&#34; 1.1&#34;在表格第0列第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");

Selenium说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");

如何正确地通过className执行findElement? 谢谢。

1 个答案:

答案 0 :(得分:2)

问题是 - 您正在使用By.className(),但在其中提供 CSS选择器。相反,请使用By.cssSelector()

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