About this question
I am a web developer and I am currently working on a project which involves extracting the data from a complex HTML structure by using the Xpath. In this take I need to retrieve the text inside q specific Log in to share your answer and help other learners.
Best Answer · By JanBask QA Expert
Answered on May 6, 2024 In the context of Selenium, you can retrieve the text inside a specific element with w unique ID by using the Xpath by constructing the XPath expression as follows:- From lxml import html # Sample HTML content Html_content = “”” This is the text inside the div. Here is the example given in java programming language:- Here is the example given in python programming language:- This is the text inside the div. “””Your answer
1 Answer
“””
# Parse the HTML content
Tree = html.fromstring(html_content)
# Construct the XPath expression
Xpath_expression = “//div[@id=’unique_id’]/text()”
# Use the XPath expression to extract the text content
Text_content = tree.xpath(xpath_expression)
# Print the extracted text content
Print(text_content[0])
Import org.jsoup.Jsoup;
Import org.jsoup.nodes.Document;
Import org.jsoup.nodes.Element;
Import org.jsoup.select.Elements;
Public class XPathExample { Public static void main(String[] args) {
String htmlContent = “This is the text inside the div.”;
// Parse the HTML content using Jsoup
Document doc = Jsoup.parse(htmlContent);
// Construct the XPath expression
String xpathExpression = “//div[@id=’unique_id’]/text()”;
// Use Jsoup’s select method with XPath expression
Elements elements = doc.select(xpathExpression);
// Extract and print the text content
For (Element element : elements) {
System.out.println(element.text());
}
}
}
From lxml import html
# Sample HTML content
Html_content = “””
# Parse the HTML content
Tree = html.fromstring(html_content)
# Construct the XPath expression
Xpath_expression = “//div[@id=’unique_id’]/text()”
# Use XPath to extract the text content
Text_content = tree.xpath(xpath_expression)
# Print the extracted text content
Print(text_content[0])More QA Testing discussions