[英]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());
恐怕在您的情况下,可能有许多元素包含类counter
和nowrap
因此您可能必须遍历它们或尝试不同的选择器来直接寻址您想要的那个。 没有网页网址很难说。
回答你原来的问题,如何按属性选择:
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.