Extract a youtube video url from a site url using jsoup

后端 未结 3 447
挽巷
挽巷 2020-12-21 23:02

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?

相关标签:
3条回答
  • 2020-12-21 23:14

    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;
    }
    
    0 讨论(0)
  • 2020-12-21 23:14

    The Best Way is

    code =youtubeUrl.substring(youtubeUrl.length() - 11);
    
    0 讨论(0)
  • 2020-12-21 23:17

    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;
    }
    
    0 讨论(0)
提交回复
热议问题