【发布时间】:2018-05-17 07:10:25
【问题描述】:
我在 java 中使用 jsoup,我试图在特定的 youtube 视频搜索中抓取第一个 href。但是,我无法找出正确的 css 查询来获取 href。如果有人能指出我正确的方向,那就太好了。 Here is the image of the html I'm trying to scrape on youtube.
以下是我尝试过的选择之一,但没有打印出任何内容。
我的代码:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.IOException;
public class WebTest
{
public static void main(String[] args)
{
try {
Document doc = Jsoup.connect("https://www.youtube.com/results?search_query=childish+gambino+this+is+america").get();
Elements musicVideoLink = doc.select("h3.title-and-badge.style-scope.ytd-video-renderer a[href]");
String linkh = musicVideoLink.attr("href");
System.out.println(linkh);
}
catch (IOException ex){ }
}
}
【问题讨论】:
-
你可以使用
#video-title -
doc.select("#video-title") 似乎不起作用。似乎还没有打印任何东西。
-
您几乎肯定是在接受一个例外。将
ex.printStackTrace();放入 catch 块中。 -
我已经加进去了,也不例外。
-
打印
doc并查看从服务器返回给您的具体内容。 Often when selector doesn't seem to work is because searched element is being placed dynamically by JavaScript later.在这种情况下,jsoup 将无法为您提供帮助,因为它不是浏览器模拟器(它不支持 JS)而是 parser,因此您需要使用其他工具,可能是 Selenium 或其他网络驱动程序.