简体   繁体   English

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

[英]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:我从网站上获取 HTML 代码,然后我想使用 Jsoup 从属性中获取值“31 983”:

<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.我试图使用doc.attr ,但没有帮助。

Jsoup uses CSS selectors to find elements in HTML source. Jsoup 使用CSS 选择器在 HTML 源代码中查找元素。 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.恐怕在您的情况下,可能有许多元素包含类counternowrap因此您可能必须遍历它们或尝试不同的选择器来直接寻址您想要的那个。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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