简体   繁体   English

Jsoup访问HTML选择标记

[英]Jsoup accessing the HTML select tag

I'm new to jsoup and having a bit of trouble with html tag. 我是jsoup的新手,并且在使用html标签方面遇到了一些麻烦。 I need to get value attribute of select list options based on a text they contain. 我需要根据它们包含的文本获取选择列表选项的值属性。 For example: 例如:

'<select id="list">
<option value="0">First value</option>
<option value="1">Second value</option>
<option value="2">Third value</option>
</select>'

Do you have an idea how I can tell jsoup to return the value "1" if it gets a "Second value" as a parameter for a search? 如果它获得“第二个值”作为搜索参数,您是否知道如何告诉jsoup返回值“1”?

Here's another solution: 这是另一个解决方案:

public String searchAttribute(Element element, String str)
{
    Elements lists = element.select("[id=list]");

    for( Element e : lists )
    {
        Elements result = e.select("option:contains(" + str + ")");

        if( !result.isEmpty() )
        {
            return result.first().attr("value");
        }
    }

    return null;
}

Test: 测试:

Document doc = Jsoup.parse(html); // html is your listed html / xml
Strign result = searchAttribute(doc, "Second value") // result = 1

This may Help You.. 这可能会帮助你......

String demo = "<select id='list'><option value='0'>First value</option><option value='1'>Second value</option><option value='2'>Third value</option></select>";


        Document document = Jsoup.parse(demo);
        Elements options = document.select("select > option");

        for(Element element : options)
        {
            if(element.text().equalsIgnoreCase("second value"))
            {
                System.out.println(element.attr("value"));
            }

        }

Try this code: 试试这段代码:

String searchValue = "Second value";
Elements options = doc.select("#list > option");
String value = "";
for (Element option : options) {
    String text = option.text();
    if (text.equals(searchValue)){
        value = option.attr("value");
    }
}

Hope it helps! 希望能帮助到你!

I think the simplest solution is: 我认为最简单的解决方案是:

 Document doc = Jsoup.parse(html);
 String value = doc.select("#list > option:contains(Second value)").val();

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

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