[英]Java and Selenium - select radio button in list by text
我正在嘗試通過文本將列表中的 select 條目。 li 條目也有 id,但我想改用文本。
我有以下 html 片段:
<fieldset felt id="bosted"
<ul class="feltliste ng-scope">
<li>
<label id="lblbostedleierKommunalt" for="bostedleierKommunalt" class="label ">
Leier kommunal bolig
</label>
</li>(verdi, tekst) in bostedTyper -->
<li>
<label id="lblbostedleierPrivat" for="bostedleierPrivat" class="label ">
Leier bolig
<div class="hjelpetekst ng-scope ng-isolate-scope" ng-class="{'hjelpetekst--utvidet': visHjelpetekst}" id="leierPrivat-hjelpetekst " ng-if="verdi === 'LEIER_PRIVAT'">
<button title="Vis hjelpetekst" type="button" ng-click="visEllerSkjulHjelpetekst($event)" aria-describedby="leierPrivat-hjelpetekst ">
<span class="bare-skjermleser" translate=""><span class="ng-scope">Vis hjelpetekst</span></span>
<est-ikon type="sporsmalstegn"><svg focusable="false"><use xlink:href="#ikon-sporsmalstegn"></use></svg>
</div>
上例中的文本條目是
雷爾公社
雷爾博利格
選項1:我正在嘗試這樣做:
driver.findElement(By.cssSelector("id='bosted' li[text=" + text + "]")).click();
我已經嘗試過“價值”和其他選項。 但我不斷收到“指定了無效或非法的選擇器”。
選項 2:我也嘗試過此解決方案,取自此處類似問題的答案:
List<WebElement> options = bosted.findElements(By.tagName("li"));
for (WebElement option : options) {
if (option.getText().equals(bosituasjon)) {
option.click();
break;
}
}
除了我認為它看起來很亂而且不是很優雅之外,它也不起作用。 在觀看測試運行時,它似乎試圖單擊頁面上目標條目上方的條目。 (雖然我不確定。)不過,它不會返回任何錯誤。
但是,它確實找到了所有文本條目,並且 if 循環命中並執行 option.click() 行。
但有些地方顯然是錯誤的,因為它沒有導航到頁面上的列表條目,並且沒有選擇該選項。
此外,如果我使用 .sendkeys(Keys.ENTER) 而不是 .click(),我會收到“元素不可交互”錯誤。
您應該在選擇器中使用value
,而不是text
。
driver.findElement(By.cssSelector("id='bosted' li[value=" + text + "]")).click();
無論如何,您可以使用在內部使用 id 的XPath選擇器。
driver.findElement(By.xpath("//fieldset[@id = 'bosted']/descendant::li[text() = '" + text + "']")).click();
使用下面定制的 xpath,它幾乎和使用 id 或類名一樣快。
driver.findElement(By.xpath("//label[contains(text(),'Leier kommunal bolig')]")).click();
CSS 選擇器不允許通過內部文本選擇元素。 請改用 XPath 選擇器。
PS - 如果您仍然需要使用第二個選項,您應該在比較之前修剪文本。 喜歡option.getText().trim().equals(bosituasjon)
因為 html 中的文本可能需要棘手的 forms..
PPS - 如果您認為您的第二個選項仍然不夠優雅,您可以應用 Steams api 並使您的代碼看起來像這樣:
List<WebElement> options = bosted.findElements(By.tagName("li"));
options.stream().filter(i -> i.getText().trim().equals(bosituasjon)).findFirst().get().click();
沒有使用 css 選擇器的文本選項。您應該改用 Xpath。
driver.findElement(By.xpath("//*[@id='bosted']//li[contains(.,'" + text + "')]")).click()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.