簡體   English   中英

JSoup,如何從動態<a href>標簽</a>返回數據

[英]JSoup, how to return data from a dynamic <a href> tag

JSoup 的新手,試圖檢索存儲在標簽中的可變值,具體來自以下網站和 html。HTML的快照

“consitituency/”之后的結果是可變的,取決於用戶的輸入。 我能夠自己檢索 h2 標簽,但不能檢索其中的信息。 目前我能得到的最好回報就是使用下面的方法標記

期望的回報將是我可以將 substring 歸結為

都柏林灣南

實際回報是

<well.col-md-4.h2></well.col-md-4.h2>

        private String jSoupTDRequest(String aLine1, String aLine3) throws IOException {
        String constit = "";
        String h2 = "h2";
     String url = "https://www.whoismytd.com/search?utf8=✓&form-input="+aLine1+"%2C+"+aLine3+"+Ireland";
        //Switch to try catch if time
        Document doc = Jsoup.connect(url)
                .timeout(6000).get();

        //Scrape elements from relevant section

        Elements body = doc.select("well.col-md-4.h2");
        Element e = new Element("well.col-md-4.h2");
        constit = e.toString();
        

        return constit;

一般來說,我對 JSoup 和抓取非常陌生。 非常感謝知道自己在做什么的人的任何意見或嘗試獲得所需結果的任何替代方法

從相關部分代碼中更改您的抓取元素,如下所示:

  • Select 首先是第一個<div class="well">元素。

     Element tdsDiv = doc.select("div.well").first();
  • Select 接下來是第一個<a>鏈接元素。 此鏈接指向選區。

     Element constLink = tdsDiv.select("a").first();
  • 通過抓取此鏈接的文本內容獲取選區名稱。

     constit = constLink.text();
import org.junit.jupiter.api.Test;

import java.io.IOException;

@DisplayName("JSoup, how to return data from a dynamic <a href> tag")
class JsoupQuestionTest {
    private static final String URL = "https://www.whoismytd.com/search?utf8=%E2%9C%93&form-input=Kildare%20Street%2C%20Dublin%2C%20Ireland";
    @Test
    void findSomeText() throws IOException {
        String expected = "Dublin Bay South";
        Document document = Jsoup.connect(URL).get();
        String actual = document.getElementsByAttributeValue("href", "/constituency/dublin-bay-south").text();
        Assertions.assertEquals(expected, actual);

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM