版权声明: https://blog.csdn.net/qq_40244755/article/details/80945625
继昨天使用Selenium+ChromeDriver爬取中国知网页面后,今天又想到了一些别的方法,就是HtmlUnit,作为一名萌新程序员,多写写总是好的,操蛋的是,还没想出好的爬取方法。
奉上jar包
<!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit -->
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.29</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit-core-js -->
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit-core-js</artifactId>
<version>2.28</version>
</dependency>
HtmlUnit就是无GUI的浏览器操作页面,本质上还是一个浏览器,所以在本质上和Selenium差别不大吧,稳定性可能存在差异。
说一下我的思路把找到特定大学的网址,检索出论文数量,和页面数量,抓取每个论文连接特有的filename,然后点击下一页,以福建农林大学为例,总共100355篇论文,我最多的时候抓取到了10339条记录,还是不完善。
下面就是代码了:
package com.qdcz.plugins;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSpan;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.List;
public class CnkiPost {
/*
* 获取动态url
* throws IOException
* InterruptedException
* */
public static void main(String args[]) throws IOException, InterruptedException {
HtmlPage page=null;
WebClient webClient=new WebClient();
// 禁止JS
//webClient.getOptions().setJavaScriptEnabled(false); 暂不需要下一页需要js渲染点击
// 禁止CSS
webClient.getOptions().setCssEnabled(false);
// 将返回错误状态码错误设置为false
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
// 启动客户端重定向
webClient.getOptions().setRedirectEnabled(true);
page=webClient.getPage("http://navi.cnki.net/knavi/PPaperDetail?pcode=CDMD&logo=GFJNU");
//休息等待数据缓冲
Thread.sleep(2000);
//获取总页数
List<HtmlSpan> span=page.getByXPath("//*[@id=\"partiallistcount2\"]");
String nums=span.get(0).asText();
int num=Integer.parseInt(nums);
System.out.println(num);
int y=0;
for(int j=0;j<num;j++){
List<HtmlAnchor> l=page.getByXPath("//*[@id=\"rightCatalog\"]/div[2]/div[2]/table/tbody/tr/td/a");
//获取论文的独有的filename
for(int i=0;i<l.size();i++){
String links=StringUtils.substringAfter(l.get(i).toString(),"FD&");
String linkss=StringUtils.substringBefore(links,"&tab");
System.out.println("--"+ i+"--"+linkss);
y++;
}
System.out.println("现在爬取到"+ (j+1)+"页");
//点击下一页
HtmlAnchor next=(HtmlAnchor) page.getByXPath("//*[@id=\"rightCatalog\"]/div[1]/div[2]/a[2]").get(0);
next.click();
Thread.sleep(3500);
}
System.out.println(y);
}
}
老大布置的活过了几天了,还是原地踏步,心塞,头疼。
诸位有什么好的想法,可以告知一下在下,不胜感激。