- 普通请求 采用Jsoup
说明: 这是访问一般网站,拿到网页源码。有的网站可能有其他更多参数需要,比如cookie等等,就在.get()前继续添加.header("cookie","xxx")方法 或者采用cookie计算工具方法
Document doc = null;try {doc =Jsoup.connect(url).userAgent(userAgent).header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36").timeout(50 * 1000).get();} catch (IOException e) {log.info("获取信息失败! 爬取url是={}", url);}
2. 比如需求某一条信息,已通过jsoup获取到了它的跳转链接,但是它是一种重定向,我们通过fiddle可以看到效果如下图
这里进行了重定向到另一个链接,同时还可以采用打开浏览器调试模式也可以在参数里看到
location就是重定向后的网站。这里如果再去通过Jsoup进行普通访问可能就会进不去。所以需要运用HtmlUnit 进行处理
/**** 获取重定向后的网站url* @param url* @return*/public static String getRedirectUrl(String url) {//设置模拟浏览器WebClient webClient = new WebClient(BrowserVersion.CHROME);//是否等待页面javaScrpit加载webClient.getOptions().setJavaScriptEnabled(true);webClient.getOptions().setRedirectEnabled(true);// js运行错误时,是否抛出异常webClient.getOptions().setThrowExceptionOnScriptError(false); webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);webClient.getOptions().setTimeout(60 * 1000); // 设置连接超时时间try {// HtmlUnit String RedirectUrl = webClient.getPage(url).getUrl().toString();if (StringUtils.isNotBlank(RedirectUrl)) {return RedirectUrl;}return null;} catch (FailingHttpStatusCodeException | IOException e) {log.error("获取重定向网站失败!");e.printStackTrace();log.error(Atom.ERROR_MSG,e.getMessage());}return null;}
在得到了转链地址后再去访问就可以了。
3.使用jsoup配置代理访问网站
String proxyIp = ips; // 你的代理API返回的ip地址int proxyPort = ; //代理ip访问的端口号String proxyUser = ""; //你的代理用户账号String proxyPass = ""; //代理用户密码//进行代理权限验证Authenticator.setDefault(new Authenticator() {@Overrideprotected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());}});Document doc =Jsoup.connect(url).proxy(JsopuUtils.getProxy(proxyIp, proxyPort)) //使用代理.header("user-agent", userAgent).timeout(210000) //这么长是因为临近一个ip结束时间.get();if (doc != null) {return doc;}return doc;
拿到document后就拿页面你要的就OK了