Android:如何使用Jsoup搜索单词或短语

Android:如何使用Jsoup搜索单词或短语,android,html,jsoup,Android,Html,Jsoup,我的问题是:如何在使用Jsoup选择的页面中搜索单词或短语。 例如,如果单词或短语在span中,我如何查找每个示例中此旁边的文本?例如链接 Html示例代码: ... <div class="div"> <span>my y favourite text </span> <a href="www.mylink.com">my link </a> </div> .... 。。。 我最喜欢的文字 .

我的问题是:如何在使用Jsoup选择的页面中搜索单词或短语。
例如,如果单词或短语在span中,我如何查找每个示例中此
旁边的文本?例如链接

Html示例代码:

   ...
  <div class="div">
  <span>my y favourite text </span>
  <a href="www.mylink.com">my link </a>
  </div>
   ....
。。。
我最喜欢的文字
....

从本例中,如何找到我最喜欢的单词,并且我还希望检索
中的链接?

目标:如果
span
包含指定的搜索单词,则在
span
href
同级
元素的属性中获取文本

一种方法是查找设置了
href
属性的
a
,该属性具有
span
元素。然后选择父元素,并在其中选择
span
元素来比较内容。对于DOM树的解析,是一个很好的选择

示例代码

String source = "<div class=\"div\"><span>my y favourite text </span><a href=\"http://www.mylink.com\">my link </a></div>" +
        "<div class=\"div\"><span>my y favourite 2 text </span><a href=\"/some-link.html\">my link 1</a></div>" +
        "<div class=\"div\"><span>my y text </span><a href=\"http://www.mylink.com\">my link 2</a></div>";

String searchWord = "favourite";

Document doc = Jsoup.parse(source, "UTF-8");
doc.setBaseUri("http://some-source.com"); // only for absolute links in local example

Element parent;
String spanContent="";
String link = "";

for (Element el : doc.select("span ~ a[href]")) {
    parent = el.parent();
    if(parent.select("span").text().contains(searchWord)){
        spanContent = parent.select("span").first().text();
        link = parent.select("a[href]").first().absUrl("href");

        System.out.println(spanContent + " -> " + link); // do something useful with the matches
    }
}

目标:如果
span
包含指定的搜索词,则获取同级
元素的
span
href
属性中的文本

一种方法是查找设置了
href
属性的
a
,该属性具有
span
元素。然后选择父元素,并在其中选择
span
元素来比较内容。对于DOM树的解析,是一个很好的选择

示例代码

String source = "<div class=\"div\"><span>my y favourite text </span><a href=\"http://www.mylink.com\">my link </a></div>" +
        "<div class=\"div\"><span>my y favourite 2 text </span><a href=\"/some-link.html\">my link 1</a></div>" +
        "<div class=\"div\"><span>my y text </span><a href=\"http://www.mylink.com\">my link 2</a></div>";

String searchWord = "favourite";

Document doc = Jsoup.parse(source, "UTF-8");
doc.setBaseUri("http://some-source.com"); // only for absolute links in local example

Element parent;
String spanContent="";
String link = "";

for (Element el : doc.select("span ~ a[href]")) {
    parent = el.parent();
    if(parent.select("span").text().contains(searchWord)){
        spanContent = parent.select("span").first().text();
        link = parent.select("a[href]").first().absUrl("href");

        System.out.println(spanContent + " -> " + link); // do something useful with the matches
    }
}

请参阅此链接。。!谢谢你…我读到了,但我不明白他是做什么的:(@shobhit,你还有其他选择吗?这个问题解决了吗?然后请接受答案或在下面的评论中发布一个跟进/澄清问题。请参考此链接…!谢谢你…我读到了,但我不明白他做了什么:(@shobhit你还有其他选择吗?这个问题解决了吗?然后请接受答案或在下面的评论中发布后续/澄清问题。在doc.select中,~Is same of>?Is same of>?与simbol?否,>代表孩子,~Is代表兄弟姐妹。请参阅:在doc.select中,~Is same of>?与simbol?否,>是相同的对于孩子,~是为了兄弟姐妹。请参见: