简体   繁体   中英

How to take value by attribute using Jsoup Java?

I am taking the HTML code from website and then I would like to take the value "31 983" from attribute using Jsoup:

<span class="counter nowrap">31 983</span>

The code below is almost ready, but do not take this value. Could you please help me?:

public class TestWebscrapper {
    private static WebDriver driver;
    @BeforeClass
    public static void before() {
        System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
        driver = new ChromeDriver();
    }
    @Test
    public void typeAllegroUserCodeIntoAllegroPageToAuthenticate() {
        String urlToAuthencicateToTypeUserCode="https://www.test.pl/";
        driver.get(urlToAuthencicateToTypeUserCode);
        Document doc = Jsoup.parse(driver.getPageSource());
        //how to take below value:
        System.out.println(doc.attr("counter nowrap"));
    }
    @AfterClass
    public static void after() {
        driver.quit();
    }
}

I was trying to use doc.attr , but does not help.

Jsoup uses CSS selectors to find elements in HTML source. To achieve what you want use:

// select the first element containing given classes
Element element = doc.select(".counter.nowrap").first();
// get the text from this element
System.out.println(element.text());

I'm afraid in your case there may be many elements containing classes counter and nowrap so you may have to iterate over them or try different selector to address directly the one you want. It's hard to tell without webpage URL.

Answering you original question, how to select by attribute:

Element element = doc.select("span[class=counter nowrap]").first();

or just:

Element element = doc.select("[class=counter nowrap]").first();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM