简体   繁体   English

Jsoup-获取仅具有指定属性及其值的HTML标记

[英]Jsoup - getting a HTML tag with ONLY the specified attributes and its values

I want to use jsoup to extract elements from a page that have only some specific attributes and values. 我想使用jsoup只有一些特定属性和值的页面中提取元素。 I have gone through the below mentioned methods and none solved my purpose well: 我经历了以下提到的方法,但没有一个能很好地解决我的目的:

  1. Jsoup's getElementsByAttributesMatching Jsoup的getElementsByAttributesMatching

  2. This format of select query: 选择查询的格式:

     doc.select("table[width=100%]").select("table[cellpadding=0]").select("table[cellspacing=0]"); 
  3. This one too: 这也是:

     doc.select("table[width=100%][cellpadding=0][cellspacing=0]"); 

When I use these methods I am getting elements which have the attributes I have mentioned plus other attributes too. 当我使用这些方法时,我得到的元素具有我提到的属性以及其他属性。 What I want are the elements with ONLY the specified attributes. 我想要的是仅具有指定属性的元素。

Is there a way to get pass this huddle? 有办法让这个杂念通过吗?

Your selector already select element having a specific value for those 3 attributes. 您的选择器已经为这3个属性选择了具有特定值的元素。 So the element has at least 3 attributes. 因此,该元素至少具有3个属性。 But if it has exactly 3 attributes, then those are the ones you specified. 但是,如果它恰好具有3个属性,则这些属性就是您指定的属性。

for (Element el: doc.select("table[width=100%][cellpadding=0][cellspacing=0]"))
    if (el.attributes().size() == 3)
        // Do something

Example

Document doc = Jsoup.parse(
    "<table width=100% cellpadding=0 cellspacing=0>OK</table>" +
    "<table width=100% cellpadding=0 cellspacing=0 height=100%>NO</table>");

for (Element el: doc.select("table[width=100%][cellpadding=0][cellspacing=0]"))
    if (el.attributes().size() == 3)
        System.out.println(el.text());

Output 产量

OK

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

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