我在Android
工作,并使用Jsoup
从互联网上清除一些数据。我无法找到确切的class
名称,其中评论位于下面定义的代码。我尝试了disqus_thread
, dsq-content
, ul-dsq-comments
和dsq-comment-body
通过转到url的源页面,但没有人返回评论。
public static void main(String[] args) {
Document d;
Elements lin = null;
String url = "http://blogs.tribune.com.pk/story/39090/i-hate-materialistic-people-beta-but-i-love-my-designer-clothes/";
try {
d = Jsoup.connect(url).timeout(20*1000).userAgent("Chrome").get();
lin = d.getElementsByClass("dsq-comment-body");
System.out.println(lin);
} catch (IOException e) {
e.printStackTrace();
}
int i=0;
for(Element l :lin){
System.out.println(""+i+ " : " +l.text());
i++;
}
}
这是因为构成注释的HTML是在页面加载后使用Javascript动态生成的。加载页面时,注释HTML不存在,因此Jsoup无法检索它。
要获得评论,您有3个选项:
1)使用一个可以执行javascript的网络爬虫。Selenium Webdriver (http://www.seleniumhq.org/projects/webdriver/)和PhantomJS (http://phantomjs.org/)是这里流行的选项。前者通过连接到浏览器实现(例如Mozilla Firefox)并以编程方式打开浏览器来工作。后者不打开浏览器,而是使用Webkit执行javascript。
2)在打开网站时拦截网络流量(这里你可以使用浏览器的内置网络选项卡),并找到获取评论的请求。您自己提出这个请求,并将相关数据提取到您的应用程序中。请记住,如果提供注释的服务器需要某种身份验证,那么这将不起作用。
3)如果注释是由具有开放访问API的专门提供者提供的,那么可以通过该API提取它们。您链接到的站点使用Disqus来处理评论部分,因此有可能挂钩到他们的API并以这种方式获取它们。