简体   繁体   中英

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.

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.

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

请修改它并通过doc将其写入您的html文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM