JSoup,如何从动态<href>标记返回数据



对JSoup非常陌生,试图检索存储在标记中的可变值,特别是来自以下网站和html。HTML快照

"选区"后的结果/";是可变的,并且依赖于用户的输入。我能够检索h2标签本身,但不是其中的信息。目前,我能得到的最好的回报就是使用下面

方法的标签期望的返回值应该是我可以将其子字符串化成

的内容

都柏林湾南部

实际返回值是

& lt; well.col - md - 4. - h2> & lt;/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和刮痧非常陌生。如果有人知道他们在做什么,或者有其他方法可以尝试得到期望的结果,我将非常感激。

按如下方式更改相关分段代码中的抓取元素:

  • 首先选择第一个<div class="well">元素。

    Element tdsDiv = doc.select("div.well").first();
    
  • 接下来选择第一个<a>link元素。此链接指向选区。

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

最新更新