Geek
Geek

Reputation: 3329

JSoup - getting url from meta data

I have a HTML code which looks like this.

<html><head><meta http-equiv="refresh" content="0;url=http://www.abc.com/event"/></head></html>

I want to use JSoup to parse this HTML and get the url value. How can I do this?

Upvotes: 2

Views: 6976

Answers (2)

Wayne
Wayne

Reputation: 60424

Parse the input and retrieve the full target text:

Document doc = Jsoup.parse("<html><head><meta http-equiv=\"refresh\" " +
        "content=\"0;url=http://www.abc.com/event\"/></head></html>");
String content = doc.getElementsByTag("meta").get(0).attr("content");

Extract only the URL portion:

System.out.println(content.split("=")[1]);

Upvotes: 4

hakyer
hakyer

Reputation: 454

You need to parse the content by yourself. Something like this:

Elements refresh = document.head().select("meta[http-equiv=refresh]");
if (!refresh.isEmpty()) {
        Element element = refresh.get(0);
        String content = element.attr("content");
        // split the content here
        Pattern pattern = Pattern.compile("^.*URL=(.+)$", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(content);
        if (matcher.matches() && matcher.groupCount() > 0) {
            String redirectUrl = matcher.group(1);
        }
}

Upvotes: 5

Related Questions