2017-07-19 125 views
0

我使用Jsoup進行HTML解析,但由於Jsoup不支持Xpath選擇器,因此我使用Xsoup這是Jsoup使用Xpath作爲選擇器。 在GitHub的自述頁:所舉的例子:如何使用Xsoup將Xpath轉換爲CSS選擇器?

@Test 
    public void testSelect() { 

     String html = "<html><div><a href='https://github.com'>github.com</a></div>" + 
       "<table><tr><td>a</td><td>b</td></tr></table></html>"; 

     Document document = Jsoup.parse(html); 

     String result = Xsoup.compile("//a/@href").evaluate(document).get(); 
     Assert.assertEquals("https://github.com", result); 

     List<String> list = Xsoup.compile("//tr/td/text()").evaluate(document).list(); 
     Assert.assertEquals("a", list.get(0)); 
     Assert.assertEquals("b", list.get(1)); 
    } 

能有人請解釋什麼需要在這個代碼工作的改變。我已經確保了我添加所需的庫asertj.jar和jsoup.jar

+0

「它將如何工作」爲了什麼?爲「真正的HTML」? ^^ – azro

+0

@azro:在github鏈接中,只有這段代碼片段沒有上下文。我想知道如何以獨立形式使用xsoup。 –

+0

你還不清楚,我沒有看到你身邊有任何障礙去嘗試你需要做的事 – azro

回答

1

這裏是工作的獨立片段:

import java.util.List; 

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 

import us.codecraft.xsoup.Xsoup; 

public class TestXsoup { 
    public static void main(String[] args){ 

      String html = "<html> 
           <div> <a href='https://github.com'>github.com</a> </div> 
           <table><tr> 
             <td>a</td> 
             <td>b</td> 
           </tr></table> 
          </html>"; 

      Document document = Jsoup.parse(html); 

      List<String> filasFiltradas = Xsoup.compile("//tr/td/text()").evaluate(document).list(); 
      System.out.println(filasFiltradas); 

    } 
} 

輸出:

[a, b] 

庫包括:

  1. xsoup-0.3.1.jar
  2. jsoup-1.103.jar