我和爬虫有个约会(java)

                                     我理解的爬虫就是通过技术手段拿到网页的源代码(java)

    方法很多种,可以通过代码发起http请求,拿到网页源代码。也可以用封装好的工具如httpclient,htmlunit。或者上大杀器phantomjs(貌似有点淘汰了)和selenium来获得源代码。。。。。

  简单的网站直接发起请求就能够拿到网页源代码,如博客园。有些网站需要一些简单的请求信息,如request-header里面的User-Agent。有些网站需要cookie验证信息。  有些丧心病狂的网站技术大多是动态加载的。拿过你不想分析他的ajax请求来艰难度日的话。可以试试selenium。

接下来讲讲每个技术的具体实现方法。有点晚了,先睡了。明天继续写。

---------------------------------------------------------------------------------------------------------------------------------------------------

写了一大半蓝屏了 win10  气炸了。

继续开工

第一种,通过java自己的代码发起http请求,获得链接。能做很多功能,但是太多了,可以被使用封装好的httpClient工具。

URL url = new URL("https://www.cnblogs.com/"); 
		URLConnection openConnection = url.openConnection();
		HttpURLConnection httpConnection = (HttpURLConnection) openConnection;
		int responseCode = httpConnection.getResponseCode();
		System.out.println(responseCode);
		InputStream inputStream = httpConnection.getInputStream();
         String html = IOUtils.toString(inputStream); //org.apache.commons.io.IOUtils;
         System.out.println(html);

第二种 使用简单的封装工具如ioutils或者jsoup获得获得源代码,适合简单的网页,没有cookie或者user-agent之类限制的网页。jsoup还可以用来解析html文档,免得写正则或则xpath之类的表达式。

String html = IOUtils.toString(new URL("https://www.cnblogs.com/"), "utf-8");//org.apache.commons.io.IOUtils;
		System.out.println(html);


	Document htmlDocument = Jsoup.parse(new URL("https://www.cnblogs.com/"), 5*1000);//org.jsoup.Jsoup;
		String text = htmlDocument.toString();
		System.out.println(text);

第三种  使用专业的http工具,如httpclient。可以设置发起的参数和获得返会的参数信息。但是解析ajax动态生成的网页就难受了

	 CloseableHttpClient httpClient = HttpClients.createDefault();
		 HttpGet get = new HttpGet("https://www.cnblogs.com/");
		 get.addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
		
		 
		 CloseableHttpResponse response = httpClient.execute(get);
		 System.out.println(response.getStatusLine().getStatusCode());
		 String html =  EntityUtils.toString(response.getEntity());// 获得网页源代码
		 System.out.println(html);
		 Header[] allHeaders = response.getAllHeaders();//获得返回的response信息
         for (Header header : allHeaders) {
			System.out.println(header);
		}		 
		 response.close();
		 httpClient.close();

第四种  htmlunit  能够处理简单的ajax生成的网页。但是因为该技术使用的浏览器内核不是主流浏览器。所以解析存在一些兼容性问题。  创建对象,按需求设置一些true,false参数。设置一个后台运行等待时间之类的。再发起请求。获得源码。大致如下。没有深入研究过

 WebClient  webClient = new WebClient(BrowserVersion.CHROME);
		  webClient.getCookieManager().setCookiesEnabled(true);
		  webClient.getOptions().setUseInsecureSSL(true);//支持https
	      webClient.getOptions().setJavaScriptEnabled(true); // 启用JS解释器,默认为true
	      webClient.getOptions().setCssEnabled(true); // css支持
		  webClient.setAjaxController(new NicelyResynchronizingAjaxController());
		  webClient.setJavaScriptTimeout(10000);//设置js运行超时时间
		  webClient.waitForBackgroundJavaScript(10000);
		  webClient.getOptions().setThrowExceptionOnScriptError(false);  
		  webClient.getOptions().setUseInsecureSSL(true);
		  webClient.getOptions().setRedirectEnabled(true);  
		  webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
		  URL url = new URL("https://www.cnblogs.com/");
          HtmlPage htmlpage = webClient.getPage(url);
          webClient.waitForBackgroundJavaScript(10000);
		  System.out.println(htmlpage.asXml());
		  webClient.close();

第五种   selenuim+chrome 浏览器   通过代码打开浏览器,模拟人的输入,点击等事件。获得源代码

(windos版本)需要安装新版的chrome浏览器,也可以用其他浏览器。这里我用chrome浏览器。 再在chrome浏览器的启动文件夹下加上chromedriver(网上下载  下载chromedirver地址)驱动。如下图。

 System.setProperty("webdriver.chrome.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");

Map<String, Object> prefs = new HashMap<String, Object>();  
prefs.put("profile.default_content_setting_values.notifications", 2);  
ChromeOptions options = new ChromeOptions();  
options.setExperimentalOption("prefs", prefs);  
//  options.addArguments("--headless","--no-sandbox","--disable-dev-shm-usage","--disable-gpu");   //这个配置意思是不开启界面,不加载gpu渲染界面。linux server运行需要次配置
options.setExperimentalOption("useAutomationExtension", false);
	        
WebDriver driver = new ChromeDriver(options);  

//到此获得了driver对象。可通过次对象 控制浏览器

通过  driver.get("https://www.xxxx.com"); 访问网站
 driver.getPageSource()   获得网页源代码


//关闭浏览器和进程 

driver.close();
driver.quit();

还可以控制输入框的清空和输入,按钮的点击之类的。

顺便说一句 ,如果部署在linux server 上,没有界面的linux 上面也是可以的。不过需要先安装chrome浏览器。然后把linux对应的驱动上传上去。代码里面指定好chromedriver的路径。

over

这排版有点不太会用呀

猜你喜欢

转载自blog.csdn.net/fangyuandoit/article/details/82669827
今日推荐