JSoup - 获取 href

JSoup - get href

我有这个 html 代码,我需要获取 link

<div class="squaresContent narrow">
  <input type="hidden" id="category_path" value="1_Komputery > Części i obudowy komputerowe > Dyski twarde" />
  <div class="productItem  first2Col first3Col first4Col first">
    <a class="productItemContent withNames  productsView" href='http://www.okazje.info.pl/km/komputery/samsung-ssd-850-evo-250gb-sata3-2-5-mz-75e250b-eu.html'>

接下来我做:

String ref = null;
for (Element el : doc.getElementsByClass("squaresContent narrow")) {
    for (Element elem : el.getElementsByClass("productItem  first2Col first3Col first4Col first")
            .select("a")) {
        ref = elem.attr("abs:href");
    }
}

但是不行。
我该怎么办?

getElementsByClass 只能与一个 class 名称作为参数一起使用。如果您需要多个 class 名称,您可以使用 css 选择器语法,其中 class 名称由 .classname 指定,即点后跟 class 名称:

String ref = null;
for (Element el : doc.select(".squaresContent.narrow")) {
  for (Element elem : el.select(".productItem.first2Col.first3Col.first4Col.first a")) {
    ref = elem.attr("abs:href");
  }
}

顺便说一句:您的循环 运行 效率不高。如果在外部或内部循环中找到多个匹配元素,您将覆盖 ref 变量。一种更优雅的方式可能是:

String ref = null;
try{
    Element aEl = doc.select(".squaresContent.narrow").last()
          .select(".productItem.first2Col.first3Col.first4Col.first a").last();
    ref = aEl.attr("abs:href");
}
catch (NullPointerException e){
    e.printStackTrace();
}

您需要 try catch,因为可能没有任何匹配的元素,这会导致 NPE。