简体   繁体   中英

How to extract string from HTML by XPath into Java?

I'm writing some automated tests with Cucumber and Selenium. Currently, I'm trying to write a function to select the passed date in a calendar picker. I need to use the current year that is displayed in the calendar when it pops up to determine some logic.

However, I can't for the life of me figure out the correct syntax to get the value of the current year into Java to work with it further. The first div is the reliably non-ambiguous tag by which I navigate to the calendar that I need to work with, I can even somehow select the year(in this case "2017") in the browser dev console, but I can't pass it into Java.

Relevant HTML:

 <ib-selector class="float-rg fblock40" ng-if="!hideYearSelector" initial-label="dateYear" next-handler="nextYear()" prev-handler="prevYear()"> <div class="calendar-month-year"> <span class="arrow-cal-left" ng-click="prevHandler()" role="button" tabindex="0"> </span> 2017 <span class="arrow-cal-right" ng-click="nextHandler()" role="button" tabindex="0"> </span> </div> </ib-selector> 

Latest attempt at extracting the year:

String currentYear = driver.findElement(By.xpath("//ib-selector[@initial-label='dateYear']/div/text()")).getAttribute("data");

Exception it generates:

org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "//ib-selector[@initial-label='dateYear']/div/text()" is: [object Text]. It should be an element.

尝试删除xpath表达式中的“ / text()”部分。

with xpath (assuming that your's path is OK, as HTML in exmple actually is not relevant):

String text = driver.findElement(By.xpath("//ib-selector[@initial-label='dateYear']/div")).getText()

or if you want to use element:

WebElement el = driver.findElement(By.xPath("//ib-selector[@initial-label='dateYear']/div"));
String text = el.getText();

here is path relevant to HTML from the example:

 String text = driver.findElement(By.cssSelector(".calendar-month-year")).getText()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM