我正在尝试抓取这个 9gag link
我尝试使用 JSoup 来获取此 HTML tag 用于获取源链接并直接下载视频。
我尝试使用此代码
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 中没有我要查找的标签,就好像页面是动态加载的,并且标签“video”尚未加载
我能做什么? 谢谢大家😊
最佳答案
让我们反转一下方法。您已经知道我们正在寻找类似 https://img-9gag-fun.9cache.com/photo/a2ZG6Yd_460svvp9.webm
的 URL
(要获取视频的 URL,您也可以在 Chrome 中右键单击该视频,然后选择“复制视频地址”)。
如果您搜索页面源代码,您会发现a2ZG6Yd_460svvp9.webm
但它存储在 <script>
内的 JSON 中。
这对于 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
不是唯一的一个,所以也许另一个更合适,例如 h265Url
或webpUrl
.
关于java - 使用java抓取网页并下载视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55868891/