How can I construct an XPath expression for targeting an element of
?

23    Asked by ColemanGarvin in QA Testing , Asked on May 6, 2024

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

element with a unique ID, however, the element is nested several levels deep within other elements. How can I construct an XPath expression to accurately Target this element and retrieve the test content? 

Answered by Diya tomar

 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.


   



“””
# 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])

Here is the example given in java programming language:-

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());
        }
    }
}

Here is the example given in python programming language:-

From lxml import html
# Sample HTML content
Html_content = “””



   

       

This is the text inside the div.


   



“””

# 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])


Your Answer