java Jsoup 在类中获取 href

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6829441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:27:32  来源:igfitidea点击:

Jsoup get href within a class

javaclasshrefjsoup

提问by Reza

I have this html code that I need to parse <a class="sushi-restaurant" href="/greatSushi">Best Sushi in town</a>

我有这个 html 代码需要解析 <a class="sushi-restaurant" href="/greatSushi">Best Sushi in town</a>

I know there's an example for jsoup that you can get all links in a page,e.g.

我知道有一个 jsoup 示例,您可以获取页面中的所有链接,例如

Elements links = doc.select("a[href]");
for (Element link : links) {
print(" * a: <%s>  (%s)", link.attr("abs:href"),
trim(link.text(), 35));
}

but I need a piece of code that can return me the href for that specific class.

但我需要一段代码来返回该特定类的 href。

Thanks guys

多谢你们

回答by Jonathan Hedley

You can select elements by class. This example finds elements with the class sushi-restaurant, then gets the absolute URL of the first result.

您可以按类选择元素。此示例查找具有 class 的元素sushi-restaurant,然后获取第一个结果的绝对 URL。

Make sure that when you parse the HTML, you specify the base URL (where the document was fetched from) to allow jsoup to determine what the absolute URL of a link is.

确保在解析 HTML 时指定基本 URL(从中获取文档的位置)以允许 jsoup 确定链接的绝对 URL 是什么。

public static void main(String[] args) {
    String html = "<a class=\"sushi-restaurant\" href=\"/greatSushi\">Best Sushi in town</a>";
    Document doc = Jsoup.parse(html, "http://example.com/");
    // find all <a class="sushi-restaurant">...
    Elements links = doc.select("a.sushi-restaurant");
    Element link = links.first();
    // 'abs:' makes "/greatsushi" = "http://example.com/greatsushi":
    String url = link.attr("abs:href");
    System.out.println("url = " + url);
}

Shorter version:

较短的版本:

String url = doc.select("a.sushi-restaurant").first().attr("abs:href");

Hope this helps!

希望这可以帮助!

回答by Rasel

Elements links = doc.select("a");
for (Element link : links) {
String attribute=link.attr("class");
if(attribute.equalsIgnoreCase("sushi-place")){
print   link.href//You probably need this
   }
}