I want to print hashtag and caption given in a post.hashtag I can print it, but in caption it showing it should be an element.
driver.findElement(By.xpath("//*[@id="react-root"]/section/main/article/div[1]/div/div/div[1]/div[1]/a/div/div[2]")).click(); List<WebElement> tags = driver.findElements(By.xpath("//a[@class='']")); for(int j=0;j<tags.size();j++) { System.out.println(tags.get(j).getText()); } WebElement caption = driver.findElement(By.xpath("/html/body/div[3]/div[2]/div/article/div[2]/div[1]/ul/div/li/div/div/div[2]/span/text()")); String Txt = caption.getText(); System.out.println(Txt);
it print all hashtag but didnt print caption
Answer
XPath locator must be resolved to a WebElement i.e. to be a Node or a NodeSet hence your XPath expression cannot return a string, you will need to remove trailing /text()
bit
Going forward using absolute XPath expressions is an antipattern as they’re very fragile and sensitive to markup changes. Consider coming up with a relative XPath query which is stable, easy to read and maintain, in your case it would be something like:
//header/descendant::a[contains(@href,'explore')]
References: