HttpURLConnection抓取
package com.app.html; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class Html { private static final String loginURL = "http://login.goodjobs.cn/index.php/action/UserLogin"; private static final String forwardURL = "http://user.goodjobs.cn/dispatcher.php/module/Personal/?skip_fill=1"; /** * 获取登录页面请求 * @param loginUrl登录URL * @param params登录用户名/密码参数 * @throws Exception */ public static String createHtml(String...params)throws Exception{ URL url = new URL(loginURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); loginHtml(conn, params); return forwardHtml(conn,url); } /** * 登录页面 * @param conn * @param params登录用户名/密码参数 * @throws Exception */ private static void loginHtml(HttpURLConnection conn, String... params) throws Exception { OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "GBK"); StringBuffer buff=new StringBuffer(); buff.append("memberName="+URLEncoder.encode(params[0], "UTF-8"));//页面用户名 buff.append("&password="+URLEncoder.encode(params[1],"UTF-8"));//页面密码 out.write(buff.toString());//填充参数 out.flush(); out.close(); } /** * 转向到定向的页面 * @param conn连接对象 * @param url重新定向请求URL * @param toUrl定向到页面请求URL * @throws Exception */ public static String forwardHtml(HttpURLConnection conn,URL url)throws Exception{ //重新打开一个连接 String cookieVal = conn.getHeaderField("Set-Cookie"); url = new URL(forwardURL); conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Foxy/1; .NET CLR 2.0.50727;MEGAUPLOAD 1.0)"); conn.setFollowRedirects(false);//置此类是否应该自动执行 HTTP 重定向 // 取得cookie,相当于记录了身份,供下次访问时使用 if (cookieVal != null) { //发送cookie信息上去,以表明自己的身份,否则会被认为没有权限 conn.setRequestProperty("Cookie", cookieVal); } conn.connect(); InputStream in = conn.getInputStream(); BufferedReader buffReader = new BufferedReader( new InputStreamReader(in,"GBK")); String line = null; String content = ""; while ((line = buffReader.readLine()) != null) { content +="\n" +line; } //IOUtils.write(result, new FileOutputStream("d:/index.html"),"GBK"); write(content, "d:/forward.html"); buffReader.close(); return content; } /** * * @param content * @param htmlPath * @return */ public static boolean write(String content, String htmlPath) { boolean flag = true; try { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlPath), "GBK")); out.write("\n" + content); out.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); return false; } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); return false; } catch (IOException ex) { ex.printStackTrace(); return false; } return flag; } public static void main(String[] args)throws Exception{ String [] params={"admin","admin12"}; System.out.println(createHtml(params)); } }
HttpClient抓取页面 未处理样式的
package com.app.html; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; public class HttpClientHtml { private static final String SITE = "login.goodjobs.cn"; private static final int PORT = 80; private static final String loginAction = "/index.php/action/UserLogin"; private static final String forwardURL = "http://user.goodjobs.cn/dispatcher.php/module/Personal/?skip_fill=1"; /** * 模拟等录 * @param LOGON_SITE * @param LOGON_PORT * @param login_Action * @param params * @throws Exception */ private static HttpClient loginHtml(String LOGON_SITE, int LOGON_PORT,String login_Action,String ...params) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); // 模拟登录页面 PostMethod post = new PostMethod(login_Action); NameValuePair userName = new NameValuePair("memberName",params[0] ); NameValuePair password = new NameValuePair("password",params[1] ); post.setRequestBody(new NameValuePair[] { userName, password }); client.executeMethod(post); post.releaseConnection(); // 查看cookie信息 CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); if (cookies != null) if (cookies.length == 0) { System.out.println("Cookies is not Exists "); } else { for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].toString()); } } return client; } /** * 模拟等录 后获取所需要的页面 * @param client * @param newUrl * @throws Exception */ private static void createHtml(HttpClient client, String newUrl) throws Exception { PostMethod post = new PostMethod(newUrl); client.executeMethod(post); post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK"); String content= post.getResponseBodyAsString(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); //IOUtils.write(content, new FileOutputStream("d:/"+format.format(new Date())+".html"),"GBK"); write(content,"d:/"+format.format(new Date())+".html"); post.releaseConnection(); } public static void main(String[] args) throws Exception { String [] params={"admin","admin123"}; HttpClient client = loginHtml(SITE, PORT, loginAction,params); // 访问所需的页面 createHtml(client, forwardURL); //System.out.println(UUID.randomUUID()); } /** * * @param content * @param htmlPath * @return */ public static boolean write(String content, String htmlPath) { boolean flag = true; try { Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlPath), "GBK")); out.write("\n" + content); out.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); return false; } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); return false; } catch (IOException ex) { ex.printStackTrace(); return false; } return flag; } }
HttpClient抓取页面处理样式的页面效果(连接服务器站点的css)
package com.app.html; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.app.comom.FileUtil; public class HttpClientHtml { private static final String SITE = "login.goodjobs.cn"; private static final int PORT = 80; private static final String loginAction = "/index.php/action/UserLogin"; private static final String forwardURL = "http://user.goodjobs.cn/dispatcher.php/module/Personal/?skip_fill=1"; private static final String toUrl = "d:\\test\\"; private static final String css = "http://user.goodjobs.cn/personal.css"; private static final String Img = "http://user.goodjobs.cn/images"; private static final String _JS = "http://user.goodjobs.cn/scripts/fValidate/fValidate.one.js"; /** * 模拟等录 * @param LOGON_SITE * @param LOGON_PORT * @param login_Action * @param params * @throws Exception */ private static HttpClient loginHtml(String LOGON_SITE, int LOGON_PORT,String login_Action,String ...params) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); // 模拟登录页面 PostMethod post = new PostMethod(login_Action); NameValuePair userName = new NameValuePair("memberName",params[0] ); NameValuePair password = new NameValuePair("password",params[1] ); post.setRequestBody(new NameValuePair[] { userName, password }); client.executeMethod(post); post.releaseConnection(); // 查看cookie信息 CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); if (cookies != null) if (cookies.length == 0) { System.out.println("Cookies is not Exists "); } else { for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].toString()); } } return client; } /** * 模拟等录 后获取所需要的页面 * @param client * @param newUrl * @throws Exception */ private static String createHtml(HttpClient client, String newUrl) throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String filePath = toUrl + format.format(new Date() )+ "_" + 1 + ".html"; PostMethod post = new PostMethod(newUrl); client.executeMethod(post); //设置编码 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK"); String content= post.getResponseBodyAsString(); FileUtil.write(content, filePath); System.out.println("\n写入文件成功!"); post.releaseConnection(); return filePath; } /** * 解析html代码 * @param filePath * @param random * @return */ private static String JsoupFile(String filePath, int random) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); File infile = new File(filePath); String url = toUrl + format.format(new Date()) + "_new_" + random+ ".html"; try { File outFile = new File(url); Document doc = Jsoup.parse(infile, "GBK"); String html="<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"; StringBuffer sb = new StringBuffer(); sb.append(html).append("\n"); sb.append("<html>").append("\n"); sb.append("<head>").append("\n"); sb.append("<title>欢迎使用新安人才网个人专区</title>").append("\n"); Elements meta = doc.getElementsByTag("meta"); sb.append(meta.toString()).append("\n"); ////////////////////////////body////////////////////////// Elements body = doc.getElementsByTag("body"); ////////////////////////////link////////////////////////// Elements links = doc.select("link");//对link标签有href的路径都作处理 for (Element link : links) { String hrefAttr = link.attr("href"); if (hrefAttr.contains("/personal.css")) { hrefAttr = hrefAttr.replace("/personal.css",css); Element hrefVal=link.attr("href", hrefAttr);//修改href的属性值 sb.append(hrefVal.toString()).append("\n"); } } ////////////////////////////script////////////////////////// Elements scripts = doc.select("script");//对script标签 for (Element js : scripts) { String jsrc = js.attr("src"); if (jsrc.contains("/fValidate.one.js")) { String oldJS="/scripts/fValidate/fValidate.one.js";//之前的css jsrc = jsrc.replace(oldJS,_JS); Element val=js.attr("src", jsrc);//修改href的属性值 sb.append(val.toString()).append("\n").append("</head>"); } } ////////////////////////////script////////////////////////// Elements tags = body.select("*");//对所有标签有src的路径都作处理 for (Element tag : tags) { String src = tag.attr("src"); if (src.contains("/images")) { src = src.replace("/images",Img); tag.attr("src", src);//修改src的属性值 } } sb.append(body.toString()); sb.append("</html>"); BufferedReader in = new BufferedReader(new FileReader(infile)); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "gbk")); String content = sb.toString(); out.write(content); in.close(); System.out.println("页面已经爬完"); out.close(); } catch (IOException e) { e.printStackTrace(); } return url; } public static void main(String[] args) throws Exception { String [] params={"admin","admin123"}; HttpClient client = loginHtml(SITE, PORT, loginAction,params); // 访问所需的页面 String path=createHtml(client, forwardURL); System.out.println( JsoupFile(path,1)); } }
HttpClient抓取页面处理样式的页面效果(从网站下载以txt格式文件写入html处理的css)
package com.app.html; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.app.comom.FileUtil; public class HttpClientHtml { private static final String SITE = "login.goodjobs.cn"; private static final int PORT = 80; private static final String loginAction = "/index.php/action/UserLogin"; private static final String forwardURL = "http://user.goodjobs.cn/dispatcher.php/module/Personal/?skip_fill=1"; private static final String toUrl = "d:\\test\\"; private static final String hostCss = "d:\\test\\style.txt"; private static final String Img = "http://user.goodjobs.cn/images"; private static final String _JS = "http://user.goodjobs.cn/scripts/fValidate/fValidate.one.js"; /** * 模拟等录 * @param LOGON_SITE * @param LOGON_PORT * @param login_Action * @param params * @throws Exception */ private static HttpClient loginHtml(String LOGON_SITE, int LOGON_PORT,String login_Action,String ...params) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT); // 模拟登录页面 PostMethod post = new PostMethod(login_Action); NameValuePair userName = new NameValuePair("memberName",params[0] ); NameValuePair password = new NameValuePair("password",params[1] ); post.setRequestBody(new NameValuePair[] { userName, password }); client.executeMethod(post); post.releaseConnection(); // 查看cookie信息 CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); if (cookies != null) if (cookies.length == 0) { System.out.println("Cookies is not Exists "); } else { for (int i = 0; i < cookies.length; i++) { System.out.println(cookies[i].toString()); } } return client; } /** * 模拟等录 后获取所需要的页面 * @param client * @param newUrl * @throws Exception */ private static String createHtml(HttpClient client, String newUrl) throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String filePath = toUrl + format.format(new Date() )+ "_" + 1 + ".html"; PostMethod post = new PostMethod(newUrl); client.executeMethod(post); //设置编码 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK"); String content= post.getResponseBodyAsString(); FileUtil.write(content, filePath); System.out.println("\n写入文件成功!"); post.releaseConnection(); return filePath; } /** * 解析html代码 * @param filePath * @param random * @return */ private static String JsoupFile(String filePath, int random) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); File infile = new File(filePath); String url = toUrl + format.format(new Date()) + "_new_" + random+ ".html"; try { File outFile = new File(url); Document doc = Jsoup.parse(infile, "GBK"); String html="<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>"; StringBuffer sb = new StringBuffer(); sb.append(html).append("\n"); sb.append("<html>").append("\n"); sb.append("<head>").append("\n"); sb.append("<title>欢迎使用新安人才网个人专区</title>").append("\n"); Elements meta = doc.getElementsByTag("meta"); sb.append(meta.toString()).append("\n"); /////////////////////////////本地css//////////////////////////// File cssFile = new File(hostCss); BufferedReader in = new BufferedReader(new FileReader(cssFile)); Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "gbk")); String content=in.readLine(); while(content!=null){ //System.out.println(content); sb.append(content+"\n"); content=in.readLine(); } in.close(); ////////////////////////////处理body标签////////////////////////// Elements body = doc.getElementsByTag("body"); ////////////////////////////处理script标签////////////////////////// Elements scripts = doc.select("script");//对script标签 for (Element js : scripts) { String jsrc = js.attr("src"); if (jsrc.contains("/fValidate.one.js")) { String oldJS="/scripts/fValidate/fValidate.one.js";//之前的css jsrc = jsrc.replace(oldJS,_JS); Element val=js.attr("src", jsrc);//修改href的属性值 sb.append(val.toString()).append("\n").append("</head>"); } } ////////////////////////////处理所有src的属性值////////////////////////// Elements tags = body.select("*");//对所有标签有src的路径都作处理 for (Element tag : tags) { String src = tag.attr("src"); if (src.contains("/images")) { src = src.replace("/images",Img); tag.attr("src", src);//修改src的属性值 } } sb.append(body.toString()); sb.append("</html>"); out.write(sb.toString()); in.close(); System.out.println("页面已经爬完"); out.close(); } catch (IOException e) { e.printStackTrace(); } return url; } public static void main(String[] args) throws Exception { String [] params={"admin","admin123"}; HttpClient client = loginHtml(SITE, PORT, loginAction,params); // 页面生成 String path=createHtml(client, forwardURL); System.out.println( JsoupFile(path,1)); } }
相关推荐
本项目涉及的是使用Apache HttpClient 4.3.3和Jsoup 1.7.3这两个开源库来实现对CSDN(China Software Developer Network)网站的模拟登录,并在成功登录后抓取用户的个人主页内容。下面将详细阐述这两个库的功能以及...
本文将深入探讨这些技术如何协同工作,以及如何利用它们来抓取和处理网页上的图片资源。 首先,Spring Boot 是一个由Pivotal团队开发的框架,它简化了基于Spring的应用程序开发过程。通过自动配置、嵌入式服务器等...
在本项目中,我们主要探讨如何使用Java编程语言,结合HtmlUtil和Jsoup库来爬取并解析知网上的中国专利数据。知网是中国最大的学术文献数据库,包含大量的专利信息,对于研究者和开发者来说,能够高效地获取这些数据...
**vParser+jsoup**是一种组合使用vParser和jsoup库来解析静态网页并提取其中数据的方法。在IT行业中,这种技术广泛应用于Web抓取、数据挖掘和自动化测试等领域。以下将详细介绍这两个库以及如何结合它们来实现所需...
对于图片,我们使用`<img>`标签的`src`属性获取URL,然后使用Java的`HttpURLConnection`或第三方库如Apache HttpClient下载图片,保存到本地,并将`src`属性替换为本地路径。 对于CSS和JavaScript,情况类似。`...
3. **异常处理**:对可能出现的网络异常、解析错误等进行捕获和处理,保持程序的健壮性。 4. **日志记录**:记录爬取过程中的重要信息,便于问题排查和分析。 5. **结果存储**:将爬取到的图片信息(如URL、文件名、...
现在我们有了图片的URL,可以使用Java的`HttpURLConnection`或者第三方库如Apache HttpClient来下载图片。以下是一个简单的下载函数: ```java public static void downloadImage(String imageUrl, String savePath...
Java网络爬虫是一种用于自动化获取网页信息的程序,它能够模拟浏览器的行为,通过发送HTTP请求并接收响应来抓取网页内容。在这个特定的场景中,爬虫需要处理登录过程,以便能够携带有效的COOKIE信息来访问受保护的...
在Java中,我们可以使用`HttpURLConnection`、`HttpClient`或`Jsoup`等库来实现模拟登录。以下是一个基本的模拟登录流程: 1. **获取登录页面**:首先,我们向登录页面发送一个GET请求,获取登录页面的HTML内容。...
在HttpClient和Jsoup结合使用时,HttpClient负责获取网页源代码,Jsoup则负责解析和提取数据,两者协同工作,实现高效的网络抓取任务。对于标签中提到的“源码”部分,深入理解这两者的内部实现可以帮助我们更好地...
在本文中,我们将深入探讨如何使用Java技术模拟登录QQ并获取QQ空间的说说。首先,我们要明白模拟登录是通过编程方式复现用户手动登录的过程,通常涉及HTTP请求、Cookie管理以及网页解析等技术。在这个场景中,我们将...
3. **模拟登录**:使用库如Apache HttpClient、Jsoup或Java内置的HttpURLConnection,可以构建模拟登录的功能。需要构造正确的HTTP请求,包含必要的cookies和session信息,以确保登录状态被正确维护。 4. **HTML...
此外,模拟登录还可能涉及到验证码识别和处理,如果百度登录有此环节,我们需要集成OCR技术(如Tesseract)来识别图片中的验证码,并将其作为参数发送。 总之,模拟百度登录是一个涉及网络请求、HTML解析、数据提交...
2. **构造请求**:使用Java的HttpURLConnection或HttpClient库,构造一个与登录页面相同的POST请求。设置请求头(如User-Agent),添加必要的Cookie信息,以及填充用户名和密码。 3. **发送请求并处理响应**:发送...
5. **存储和处理数据**:抓取的数据通常需要存储(如CSV、JSON文件)或进一步处理(如数据分析、机器学习)。Java提供了很多库,如Apache Commons CSV、Jackson等,来帮助处理这些任务。 6. **遵守robots.txt**:在...
Jsoup 是一个非常流行的Java库,用于处理HTML和XML文档,它提供了丰富的API来抓取、解析和操作网页内容。...通过实践,我们可以提升网络爬虫的技能,同时理解如何在遵守规范的前提下,有效地抓取和处理网页数据。
6. **实战应用**:在压缩包中的`HtmlParse`文件中,可能包含了示例代码,演示了如何结合JSOUP和Java的网络请求功能实现模拟登录。通过阅读和理解这段代码,你可以更深入地了解上述步骤的实际操作。 总的来说,Java...
【标签】中的“Java模拟QQ”特别强调了Java在模拟登录中的应用,这可能涵盖了网络爬虫的相关技术。虽然模拟登录不完全等同于爬虫,但两者都涉及到网络数据的抓取。理解如何使用Jsoup或HttpClient库解析HTML页面,...
在IT行业中,模拟登录是一项常见的任务,特别是在自动化测试、数据抓取或数据分析等场景下。本项目名为"Java模拟登录百度Demo",旨在通过Java编程语言实现对百度网站的自动登录功能。在这个教程中,我们将深入探讨...
在"对指定页面进行抓取"的场景中,我们主要关注GET请求,这是最简单且最常见的网页抓取方式。 下面,我们将详细阐述如何使用`HttpURLConnection`进行网页抓取: 1. **建立连接**:首先,我们需要创建一个URL对象,...