Jsoup get CSS selector for any DOM element example

Jsoup get CSS selector for any DOM element example shows how to get a CSS selector for any DOM element using the Google Chrome browser.

How to get a CSS selector for any DOM element using Chrome?

CSS selectors are very useful especially if you are using an HTML parser library like Jsoup. It becomes very difficult to determine the exact selector while trying to parse or scrap a complex website having tons of nested HTML elements. That is where Google Chrome becomes handy.

You do not need to spend time trying to understand the structure of the complex HTML. Here is how to do it using Google Chrome in under a minute.

Step 1:

Open the webpage you are trying to parse or scrap in Google Chrome.

Step 2:

Right-click on the element for which you want the CSS selector and select the “Inspect” menu item.

_jsoup_extract_css_selector1

Step 3:

In the developer tools window, right-click again on the selected element’s source, select “Copy” and then select the “Copy selector” menu item.

_jsoup_extract_css_selector2

Paste the copied CSS selector in your program. Here is the CSS selector value which Chrome gave me for the selected link element.

Similarly, you can also generate XPATH by selecting Copy > Copy XPath menu item.

This example is a part of the Jsoup tutorial with examples.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping