【问题标题】:How to get one "a href" out of many in one html class with jSoup如何使用 jSoup 从一个 html 类中的多个中获取一个“a href”
【发布时间】:2015-06-27 02:51:31
【问题描述】:

我必须将 HTML 中的所有文本元素提取到 Java 字符串中。但在单独的字符串中。

我有以下代码:

<div class="sb-spieldaten">
    <p class="sb-datum hide-for-small">
        <a href="/jumplist/spieltag/wettbewerb/C1/saison_id/2014/spieltag/2">2. Spieltag</a>
        &nbsp;&nbsp;|&nbsp;&nbsp;
        <a href="/aktuell/waspassiertheute/aktuell/new/datum/2014-07-26">Sa., 26.07.2014</a>
        &nbsp;&nbsp;|&nbsp;&nbsp;17:45 Uhr
    </p>
    <p class="sb-datum show-for-small">
        <a href="/jumplist/spieltag/wettbewerb/C1/saison_id/2014/spieltag/2">2. Spieltag</a>
        <br />
        <a href="/aktuell/waspassiertheute/aktuell/new/datum/2014-07-26">26.07.2014</a>
        <br>
        17:45 Uhr
    </p>
    <div class="ergebnis-wrap">
        <div class="sb-ergebnis">
            <div class="sb-endstand">2:3
                <div class="sb-halbzeit">(<span>2:</span>2)
                </div>
            </div>
        </div>
    </div>
    <p class="sb-zusatzinfos">
        <span class="hide-for-small">
            <a href="/stadion/stadion/verein/504/saison_id/2014">Letzigrund</a>
            &nbsp;&nbsp;|&nbsp;&nbsp;
            <strong>4.200 Zuschauer</strong>
            <br />
        </span>
        <strong>Schiedsrichter:</strong>
        <br class="show-for-small" />
        <a title="Fedayi San" href="/fedayi-san/profil/schiedsrichter/4791">Fedayi San</a>
    </p>
</div>

我使用:

Elements myText = doc.getElementsByClass("sb-spieldaten");
String myString = myText.select(a.sb-datum.hide-for-small").text();

但是我提取了“hide-for-small”类中的所有字符串。所以我得到的答案是: 2. Spieltag |萨,2014 年 7 月 26 日 | 17:45 Uhr 2. Spieltag 26.07.2014 17:45 Uhr Letzigrund | 4200 Zuschauer Schiedsrichter:Fedayi San

如何只获得其中一个字符串?我无法理解 .getElementsByClass("...") 找到它。有没有办法提取特定的“a href”元素?还是我必须使用 .split() 方法?

【问题讨论】:

  • 你想要哪个a href 元素?
  • 大家。但是当我知道如何提取一个时,我会以同样的方式处理其他的。
  • 你要提取的那个必须有一些独特的属性。这里的属性通常链接到CSS query [public Elements select(String cssQuery)]。

标签: java html jsoup href extract


【解决方案1】:

例如代码片段

Document abc = Jsoup.connect("http://www.abc.in/").timeout(0).get();
Elements ee = abc.select("a[href*=xyz]");// all hrefs containing xyz substring 
String xyz = ee.first().attr("abs:href");

【讨论】:

    【解决方案2】:

    "元素 myText = doc.getElementsByClass(x);"

    查看@相关网页的 CSS,找到分配给相关元素的 css 元素的类 ID。

    【讨论】:

      猜你喜欢
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      相关资源
      最近更新 更多