簡體   English   中英

如何使用 Jsoup Java 按屬性取值?

[英]How to take value by attribute using Jsoup Java?

我從網站上獲取 HTML 代碼,然后我想使用 Jsoup 從屬性中獲取值“31 983”:

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

下面的代碼差不多准備好了,但是不要取這個值。 請你幫助我好嗎?:

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

我試圖使用doc.attr ,但沒有幫助。

Jsoup 使用CSS 選擇器在 HTML 源代碼中查找元素。 要實現您想要的用途:

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

恐怕在您的情況下,可能有許多元素包含類counternowrap因此您可能必須遍歷它們或嘗試不同的選擇器來直接尋址您想要的那個。 沒有網頁網址很難說。

回答你原來的問題,如何按屬性選擇:

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

要不就:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM