2013-08-21 67 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); 

     }