Reputation: 666
Could anybody help how to solve this dilemma
I have this code:
<div>
<a href="/cars/102392-2">Link</a>
<span class="make">Chevrolet</span><br>
<span class="year">1956</span><br>
<span class="price">$20,000</span><br>
</div>
<div>
<a href="/cars/152933-11">Link</a>
<span class="make">Ford</span><br>
<span class="year">1958</span><br>
<span class="price">$21,000</span><br>
</div>
I need get the link for example Fords with the year greater then 1950.
Presently, I am using following xpath:
//*[text()='Ford' and .//text()>'1950']//parent::a
And this doesn't work! Have you any idea ?
Upvotes: 3
Views: 1546
Reputation: 89285
This is one possible XPath :
//div[span/text()='Ford' and span/text()>1950]/a
Basically the XPath check if div
has child span
with text equals 'Ford' and another child span
with value greater than 1950. Then from such div
that match the two criteria above, return child a
element.
Better yet, only check span
with class 'make' for manufacturer and span
with class 'year' for manufacturing year :
//div[span[@class='make']='Ford' and span[@class='year']>1950]/a
Upvotes: 3
Reputation: 910
You can write a generic method to get the required links, as shown below:
public static List<WebElement> getLinks(String linkText, int year) {
List<WebElement> links = driver.findElements(By.xpath("//a[text()='" + linkText + "']/following-sibling::span[1]"));
List<WebElement> linksGreaterThanRequiredYear = new ArrayList<WebElement>();
for (WebElement link : links) {
if (Integer.parseInt(link.getText()) > year)
linksGreaterThanRequiredYear.add(link);
}
return linksGreaterThanRequiredYear;
}
Hence, if you want to get the Fords with year greater than 1950, you can call above method in following way:
List<WebElement> fordsWithYearGreaterThan1950 = getLinks("Ford", 1950);
Above method can be further enhanced to include less than criteria as well. Let me know, if you have any further queries.
Upvotes: 0