Total Pageviews

2018/03/13

[jsoup] How to use jsoup selector to retrieve value?

Problem
I try to get "2412 中華電" from this page: https://goodinfo.tw/StockInfo/StockDetail.asp?STOCK_ID=2412


jsoup provide select method to find elements that match the Selector CSS query, with this element as the starting context. Matched elements may include this element, or any of its children. But how to define the CSS selector?


1
2
3
4
5
6
    public static void main(String[] args) throws IOException {
        String cssSelector = "???";
        String url = "https://goodinfo.tw/StockInfo/StockDetail.asp?STOCK_ID=2412";
        Document doc = Jsoup.connect(url).get();
        String name = doc.select(cssSelector).text();
    }


How-To
You can use Google Chrome to help you get the CSS Selector:

Here has the sample code:
1
2
3
4
5
6
    public static void main(String[] args) throws IOException {
        String cssSelector = "body > table:nth-child(3) > tbody > tr > td:nth-child(3) > table > tbody > tr:nth-child(1) > td > table:nth-child(1) > tbody > tr > td > table > tbody > tr:nth-child(1) > td > span:nth-child(1) > a";
        String url = "https://goodinfo.tw/StockInfo/StockDetail.asp?STOCK_ID=2412";
        Document doc = Jsoup.connect(url).get();
        String name = doc.select(cssSelector).text();
    }




No comments: