2013-08-21 63 views
1

你好,我已經嘗試了這些答案:How to replace a tag using jsoupReplace HTML tags using jsoup我的情況失敗。我正在用JSoup解析一個網站,並且我跑遍了字母外觀的GIF圖像。幸運的是,這些gif圖像具有特定的名稱,例如,字母「A」的a.gif。使用JSoup替換字母標記

HTML輸入:

<body> 
    <p><img src="http://www.example.com/images/a.gif" align="left">mong us!</p> 
</body> 

所需的輸出:

<body> 
    <p>Among us!</p> 
</body> 

我的Java代碼(下)不打印預期輸出:

Document document = Jsoup.connect("http://www.example.com").get(); 
if(document.select("img").attr("src").contains("a.gif")) 
    { 
    document.select("img").get(0).replaceWith(new Element(Tag.valueOf("img"), "A")); 
    } 

謝謝你的幫助。

回答

1

使用TextNode而不是Element

Document document = Jsoup.parse(html); 
if (document.select("img").get(0).attr("src").contains("a.gif")) { 
    document.select("img").get(0).replaceWith(new TextNode("A", "")); 
    System.out.println(document); 
} 

上述代碼可以按照預期打印html。

+0

謝謝你,它的工作原理與未成年另外,如果我在IF語句。獲得加(0) ; 'if(document.select(「img」)。get(0).attr(「src」)。contains(「a.gif」))' – Rod

+0

@Rodo是的,我錯過了'.get(0)'in我的'IF'聲明。我會在我的回答中糾正它。謝謝。 –

+0

@JasonCao我想替換圖像的路徑。所以我在本地保存圖像,並從本地路徑而不是服務器上的路徑顯示它。 – anup

2

試試吧!

Elements elements = doc.select("img[src$=a.gif]"); 
    for(Element element : elements) 
    { 
     element.replaceWith(new TextNode("A", null)); 
    } 
+0

它的工作原理,但我需要一個IF語句提示,因爲我可以運行不同的字母。謝謝。 – Rod

+0

謝謝@Niranjan!看起來這只是這樣做的方法。 ''A'會是'element.text()'。 –

1

試試這個:

Document document = Jsoup.parse(html); 
if (document.select("img").get(0).attr("src").contains("a.gif")) { 
    document.select("img").get(0).replaceWith(new TextNode("A", null)); 
} 
+0

你能解釋爲什麼這個工程? – Daniel

+1

謝謝,如果我添加IF語句.get(0); 'if(document.select(「img」)。get(0).attr(「src」)。contains(「a.gif」))' – Rod

+0

謝謝@rodo我編輯了代碼。 –

1

試試這個:

Document document = Jsoup.connect("http://www.example.com").get(); 
    if(document.select("img").attr("src").contains("a.gif")) 
     { 
     String result =""; 
     String src =document.select("img").attr("src").text(); 
     result = src.replace(src,"A"); 
     System.out.println(result); 

     }