【问题标题】:JSoup - get hrefJSoup - 获取href
【发布时间】:2016-01-15 13:59:21
【问题描述】:

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

<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");
    }
}

但它不起作用。
我该怎么办?

【问题讨论】:

  • 你试过调试吗?

标签: java html-parsing jsoup


【解决方案1】:

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

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。

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 2016-06-18
    • 2011-10-13
    • 1970-01-01
    • 2017-09-29
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多