1

I had this code working for the same site but they changed the theme and now i'm struggling. What could i be doing wrong here to get the url of the youtube video? Here's my approach. The example link of the site is http://kabumbu.co.tz/mahojiano-na-masau-bwire/

Element video = doc.select("div.single-archive iframe").first() ;
          videourl = video.attr("src");
Nasz Njoka Sr.
  • 1,138
  • 16
  • 27

3 Answers3

2

The code is correct so far but I just was wrongly extracting the video id from the video url. Using this method worked

public static String extractVideoId(String ytUrl) {
    String vId = null;
    Pattern pattern = Pattern.compile(".*(?:youtu.be\\/|v\\/|u\\/\\w\\/|embed\\/|watch\\?v=)([^#\\&\\?]*).*");
    Matcher matcher = pattern.matcher(ytUrl);
    if (matcher.matches()){
        vId = matcher.group(1);
    }
    return vId;
}
Stephan
  • 41,764
  • 65
  • 238
  • 329
Nasz Njoka Sr.
  • 1,138
  • 16
  • 27
0

Alternatively, here is a Jsoup only solution:

/**
 * 
 * /!\ Exceptions raised by this method are NOT logged. /!\ 
 * 
 * @param youtubeUrl
 * @return videoId or null if an exception occured
 * 
 */
public static String extractVideoId(String youtubeUrl) {
    String videoId = null;

    try {
        Document videoPage = Jsoup.connect(youtubeUrl).get();

        Element videoIdMeta = videoPage.select("div[itemtype=http://schema.org/VideoObject] meta[itemprop=videoId]").first();
        if (videoIdMeta == null) {
            throw new IOException("Unable to find videoId in HTML content.");
        }

        videoId = videoIdMeta.attr("content");
    } catch (Exception e) {
        e.printStackTrace(); // alternatively you may log this exception...
    }

    return videoId;
}
Stephan
  • 41,764
  • 65
  • 238
  • 329
0

The Best Way is

code =youtubeUrl.substring(youtubeUrl.length() - 11);