Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set attributes of tags of HTML using JSoup

How to set attributes of tags of HTML using JSoup?

I want to set the attribute->"src" of tag->"img" in Java using Jsoup Library.

Elements img_attributes = doc.select("img[src^=/im]");
for(Element img_attribute: img_attributes)
{

String s = img_attribute.attr("src");
System.out.println(s);
}

This code prints the src values. I want to change the src values.

like image 733
user1993469 Avatar asked Jan 24 '13 05:01

user1993469


2 Answers

You cen do this with attr() method in both ways: loop or directly on the Elements object:

// In a loop
for( Element img : doc.select("img[src]") )
{
    img.attr("src", "your-source-here"); // set attribute 'src' to 'your-source-here'
}

// Or directly on the 'Elements'
doc.select("img[src]").attr("src", "your-value-here");

In fact both solutions are the same.

like image 169
ollo Avatar answered Nov 18 '22 19:11

ollo


check http://jsoup.org/apidocs/org/jsoup/nodes/Element.html#attr%28java.lang.String,%20java.lang.String%29 i think function

public Element attr(String attributeKey,
                    String attributeValue)

is useful for you

like image 22
Fathah Rehman P Avatar answered Nov 18 '22 19:11

Fathah Rehman P