2016-08-19 238 views
2

我正在开发一个项目,我需要解析HTML以从网页中提取数据。我在Java中使用Jsoup。我需要从以下内容中提取数据。解析HTML href属性

<tr> 
      <td><small><a href="http://www.timeanddate.com/worldclock/fixedtime.html?iso=20160821T2100&amp;p1=248" target="_blank">2016/08/21 21:00</a></small></td> 
      <td><small><a href="https://agc003.contest.atcoder.jp">AtCoder Grand Contest 003</a></small></td> 

</tr> 

我可以得到值的比赛名称和时间,但如何提取网址。我想要得到比赛的URL https://agc003.contest.atcoder.jp 如何得到这个?

编辑: 这里是我的代码

private void getAC() throws IOException { 

    Document doc = Jsoup.connect("https://atcoder.jp/").userAgent(Desktop.getDesktop().toString()).get(); 
    Element table = doc.getElementsByClass("table-responsive").get(1); 
    Elements contestStartTime = table.getElementsByTag("td"); 
    int cnt = 1; 
    for (Element i : contestStartTime) { 
     System.out.println(cnt + ". " + i.html()); 
     cnt++; 
    } 

} 

+0

我不是f熟悉JSoup或Java,但我会加载文件,逐行读取它并使用正则表达式模式来搜索您需要的​​,然后从该行解析Url。 – dinotom

+0

你可以添加你的代码来获取比赛名称和时间吗? – TDG

+0

由于标签似乎没有一个id或anyhing目标与他们,我真的不知道。但是,一旦找到元素就很容易获取URL。 'Elements.attr(“href”)'应该得到值 –

回答

2

JSoup对DOM处理丰富的API,查找此功能:

Element content = doc.getElementById("content"); 
Elements links = content.getElementsByTag("a"); 
for (Element link : links) { 
    String linkHref = link.attr("href"); 
    String linkText = link.text(); 
} 

你也可以得到你的链接这样

Elements links = doc.select("table a[href]"); 
+0

谢谢。它正在工作! :d –