HttpClient直接获取页面信息html
使用方法:java
使用HttpClient发送请求、接收响应很简单,通常须要以下几步便可。node
1. 建立HttpClient对象。web
2. 建立请求方法的实例,并指定请求URL。若是须要发送GET请求,建立HttpGet对象;若是须要发送POST请求,建立HttpPost对象。api
3. 若是须要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。数组
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。服务器
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可经过该对象获取服务器的响应内容。ide
6. 释放链接。不管执行方法是否成功,都必须释放链接函数
public String cawl(String url){ try { CloseableHttpClient httpClient = HttpClientBuilder.create().build();//初始化 CloseableHttpResponse httpResponse = httpClient.execute(new HttpGet(url));//获取页面信息 String result = EntityUtils.toString(httpResponse.getEntity());//将对象转换成字符串输出 return result; } catch (IOException e) { throw new RuntimeException(e); } }
//经过parse解析html字符串
Document doc = Jsoup.parse(result);
使用Jsoup的connect().get();fetch
Document doc = Jsoup.connect(url).get()//须要try...catch...抛出IO流异常
说明
connect(String url)
方法建立一个新的 Connection
, 和 get()
取得和解析一个HTML文件。若是从该URL获取HTML时发生错误,便会抛出 IOException,应适当处理。
了解更多参考Jsoup的API文档:http://www.open-open.com/jsoup/load-document-from-url.htm
附主函数:
package test; import imple.Impl; import model.Model; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; public class TestMain { public static int i = 0; Impl impl = new Impl(); List<Model> models = impl.getNovel("http://www.biquge.tw/0_5/"); public static void main(String[] args) { MyThread tw = new TestMain().new MyThread(); for(int j = 0;j<10;j++)new Thread(tw).start(); } class MyThread implements Runnable{ public void run() { while (i!=models.size()) { // String r = impl.cawl(models.get(i).getUrl()); Document d = null; try { d = Jsoup.connect(models.get(i).getUrl()).get(); } catch (IOException e) { e.printStackTrace(); } models.get(i).setContent(d.select("#content").text()); File file = new File("E:\\完美世界\\" + models.get(i).getTitle() + ".txt"); FileWriter writer = null; try { writer = new FileWriter(file); writer.write(models.get(i).getContent()); writer.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("第" + (i + 1) + "章输出完毕"); i++; } } } }
总结
以前没有接触Jsoup,对于怎么获取http请求,以及获取页面信息都是使用的URLConnect,今天使用这两种实现了小说的抓取,今天有几个问题,当我想把URL,章节名,以及内容所有都储存到数组列表中,可是须要的时间过长,并且抓取的过程容易出错,由于后边换成单线程抓取小说的时候,我采用一个for循环将小说储存进数组列表的同时也在本地建立一个txt文档,输出成功就会返回xxx输出成功,也出现了一个问题,当程序抓取到1100章左右的时候报出了时间超时的问题,彷佛Jsoup链接URL的方法connect()有时间限制,最后我使用十个线程同时抓取小说方得成功。