Reputation: 117
Hello I have tried these answers: How to replace a tag using jsoup and Replace HTML tags using jsoup to my case unsuccessfully. I am parsing a website with JSoup and I ran accross letter-look GIF images. Fortunately those gif images have a specific name, e.g. a.gif for letter "A".
HTML input:
<body>
<p><img src="http://www.example.com/images/a.gif" align="left">mong us!</p>
</body>
Desired output:
<body>
<p>Among us!</p>
</body>
My java code (below) does not print the expected output:
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"));
}
Thank you for your help.
Upvotes: 1
Views: 5612
Reputation: 3368
try this:
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));
}
Upvotes: 1
Reputation: 989
Using TextNode
instead of 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);
}
The above code can print html as you expected.
Upvotes: 2
Reputation: 527
Try This:
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);
}
Upvotes: 2
Reputation: 1834
Try this!!
Elements elements = doc.select("img[src$=a.gif]");
for(Element element : elements)
{
element.replaceWith(new TextNode("A", null));
}
Upvotes: 3