How do I update an attribute for multiple elements with jsoup?

To update an attribute for multiple elements using jsoup, you can use the Elements class, which represents a list of elements. You can iterate through each element in the list and use the attr(String key, String value) method to update the attribute for each element.

Here is a step-by-step example in Java:

  1. Select the elements you want to update using a CSS-like query.
  2. Iterate through the selected elements.
  3. Use the attr method on each element to update the attribute.
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class UpdateAttributesWithJsoup {
    public static void main(String[] args) {
        String html = "<div>" +
                      "  <a href='old_link1.html'>Link 1</a>" +
                      "  <a href='old_link2.html'>Link 2</a>" +
                      "  <a href='old_link3.html'>Link 3</a>" +
                      "</div>";

        // Parse the HTML string into a Document object
        Document doc = Jsoup.parse(html);

        // Select all anchor tags <a>
        Elements links = doc.select("a");

        // Iterate over the selected elements and update the "href" attribute
        for (Element link : links) {
            // Here we are prepending "https://example.com/" to each href attribute
            link.attr("href", "https://example.com/" + link.attr("href"));
        }

        // Output the modified HTML
        System.out.println(doc.html());
    }
}

In the example above, each href attribute of the anchor tags (<a>) is updated to prepend "https://example.com/" to the original href value.

Remember to include jsoup in your project dependencies if you're using Maven:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.14.3</version>
</dependency>

If you're using Gradle:

implementation 'org.jsoup:jsoup:1.14.3'

Replace 1.14.3 with the latest version available at the time you are adding the dependency.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon