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.
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.
Paste the copied CSS selector in your program. Here is the CSS selector value which Chrome gave me for the selected link element.
1 |
#rso > div:nth-child(1) > div:nth-child(2) > div > h3 > a |
Similarly, you can also generate XPATH by selecting the Copy > Copy XPath menu item.
Please also see how to set Jsoup proxy example to learn more about that.
This example is a part of the Jsoup tutorial with examples.
Please let me know your views in the comments section below.