首页 > 解决方案 > 用java抓取网页并下载视频

问题描述

我正在尝试抓取这个 9gag链接

我尝试使用 JSoup 获取此 HTML标记 以获取源链接​​并直接下载视频。

我试过这段代码

    public static void main(String[] args) throws IOException {
        Response response= Jsoup.connect("https://9gag.com/gag/a2ZG6Yd")
                   .ignoreContentType(true)
                   .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")  
                   .referrer("https://www.facebook.com/")
                   .timeout(12000) 
                   .followRedirects(true)
                   .execute();

        Document doc = response.parse();
        System.out.println(doc.getElementsByTag("video"));
    }

但我什么也得不到

我当时试过这个

    public static void main(String[] args) throws IOException {
        Response response= Jsoup.connect("https://9gag.com/gag/a2ZG6Yd")
                   .ignoreContentType(true)
                   .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")  
                   .referrer("https://www.facebook.com/")
                   .timeout(12000) 
                   .followRedirects(true)
                   .execute();

        Document doc = response.parse();
        System.out.println(doc.getAllElements());
    }

我注意到在 HTML 中没有我正在寻找的标签,好像页面是动态加载的并且标签“视频”还没有加载

我能做什么?谢谢你们

标签: javaweb-scrapingjsoup

解决方案


让我们反转方法。您已经知道我们正在寻找类似的 URL https://img-9gag-fun.9cache.com/photo/a2ZG6Yd_460svvp9.webm (要获取视频的 URL,您也可以在 Chrome 中右键单击它并选择“复制视频地址”)。

如果您搜索页面源代码,您会找到a2ZG6Yd_460svvp9.webm,但它存储在 JSON 中<script>

在此处输入图像描述

这对 Jsoup 来说不是一个好消息,因为它无法解析,但我们可以使用简单的正则表达式来获取此链接。URL 已转义,因此我们必须删除反斜杠。然后就可以使用 Jsoup 下载文件了。

    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("https://9gag.com/gag/a2ZG6Yd").ignoreContentType(true)
                .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
                .referrer("https://www.facebook.com/").timeout(12000).followRedirects(true).get();

        String html = doc.toString();

        Pattern p = Pattern.compile("\"vp9Url\":\"([^\"]+?)\"");
        Matcher m = p.matcher(html);
        if (m.find()) {
            String escpaedURL = m.group(1);
            String correctUrl = escpaedURL.replaceAll("\\\\", "");
            System.out.println(correctUrl);
            downloadFile(correctUrl);
        }
    }

    private static void downloadFile(String url) throws IOException {
        FileOutputStream out = (new FileOutputStream(new File("C:\\file.webm")));
        out.write(Jsoup.connect(url).ignoreContentType(true).execute().bodyAsBytes());
        out.close();
    }

另请注意,这vp9Url不是唯一的一个,所以也许另一个会更合适,例如h265Urlor webpUrl


推荐阅读