java抓取HTML页面的数据(淘宝页面),

xiaoxiao2021-02-28  32

--第1步:获取http---第2步用正则表达式进行解析

第1步:

package com.yanshu.tools; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class HttpUtility { /** * 向指定URL发送GET方法的请求 * @param taskurl *            发送请求的URL * @param param *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(Object taskurl, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = taskurl + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); //connection.setRequestProperty("referer", "https://item.taobao.com/item.htm?spm=a219r.lm874.14.1.7FfR2G&id=531878100031&ns=1&abbucket=17"); // connection.setRequestProperty("referer", "https://www.taobao.com"); connection.setRequestProperty("Content-type", "text/html"); connection.setRequestProperty("upgrade-insecure-requests", "1"); //connection.setRequestProperty("projectId", "1318"); //connection.setRequestProperty("target", "_blank"); connection.setRequestProperty("Cookie", "UM_distinctid=15ce85940eeb6-0ededb7ab12ab7-714d2542-1fa400-15ce85940f03a3; thw=cn; l=AoeH71vtTJplFHodyW9Km6LWlzBRNFtu; ali_apache_id=11.131.220.163.150770215638.249204.2; miid=542152054597054537; _cc_=UtASsssmfA==; tg=0; ali_ab=180.172.239.236.1504257044497.3; cna=qj6tEaUwR2gCAbSs7+wVMbzj; t=449d46ab83aeedc87c00dd3445b7c1a1; _m_h5_tk=9848cddbcb8e9e9fbcba777beaf178e3_1513319477951; _m_h5_tk_enc=098be3ca7eefbf0d0dc4ca8d4373a416; hng=CN|zh-CN|CNY|156; mt=ci=0_0; cookie2=2d568166cf6798789cb6dfe308656172; v=0; _tb_token_=55e8bbe9576ed; alitrackid=www.taobao.com; lastalitrackid=www.taobao.com; ctoken=lD359uPelBrHdgHqQMaXp4p-render; isg=Av7-BVfyKJPOGn86hKhLA9_JTxSAl8CtYYz2VqgGYcE8S58lEM0MyDpptyF8; JSESSIONID=47BB19E15ADB5FD76C986F288B1DA2BE"); // connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); connection.setRequestProperty("cache-control", "max-age=0"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // connection // .setRequestProperty( // "user-agent", // "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.7 Safari/537.36"); // connection // .setRequestProperty( // "user-agent", // "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 /* for (String key : map.keySet()) { //System.out.println(key + "--->" + map.get(key)); }*/ // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; //System.out.println(line); } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 发送POST方法的请求 * @param url *            发送请求的 URL * @param param *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }

---第2步

package com.yanshu.tools; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexUtils2 { /** * 验证Email * @param email *            email地址,格式:zhangsan@zuidaima.com,zhangsan@xxx.com.cn, *            xxx代表邮件服务商 * @return 验证成功返回true,验证失败返回false */ public static boolean checkEmail(String email) { String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; return Pattern.matches(regex, email); } /** * 验证身份证号码 * @param idCard *            居民身份证号码15位或18位,最后一位可能是数字或字母 * @return 验证成功返回true,验证失败返回false */ public static boolean checkIdCard(String idCard) { String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}"; return Pattern.matches(regex, idCard); } /** * 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港)) * @param mobile *            移动、联通、电信运营商的号码段 *            <p> *            移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡) *            、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用) *            </p> *            <p> *            联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g) *            </p> *            <p> *            电信的号段:133、153、180(未启用)、189 *            </p> * @return 验证成功返回true,验证失败返回false */ public static boolean checkMobile(String mobile) { String regex = "(\\+\\d+)?1[34578]\\d{9}$"; return Pattern.matches(regex, mobile); } /** * 验证固定电话号码 * @param phone *            电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447 *            <p> *            <b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 *            的一位或多位数字, 数字之后是空格分隔的国家(地区)代码。 *            </p> *            <p> *            <b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号—— *            对不使用地区或城市代码的国家(地区),则省略该组件。 *            </p> *            <p> *            <b>电话号码:</b>这包含从 0 到 9 的一个或多个数字 *            </p> * @return 验证成功返回true,验证失败返回false */ public static boolean checkPhone(String phone) { String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; return Pattern.matches(regex, phone); } /** * 验证整数(正整数和负整数) * @param digit *            一位或多位0-9之间的整数 * @return 验证成功返回true,验证失败返回false */ public static boolean checkDigit(String digit) { String regex = "\\-?[1-9]\\d+"; return Pattern.matches(regex, digit); } /** * 验证整数和浮点数(正负整数和正负浮点数) * @param decimals *            一位或多位0-9之间的浮点数,如:1.23,233.30 * @return 验证成功返回true,验证失败返回false */ public static boolean checkDecimals(String decimals) { String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; return Pattern.matches(regex, decimals); } /** * 验证空白字符 * @param blankSpace *            空白字符,包括:空格、\t、\n、\r、\f、\x0B * @return 验证成功返回true,验证失败返回false */ public static boolean checkBlankSpace(String blankSpace) { String regex = "\\s+"; return Pattern.matches(regex, blankSpace); } /** * 验证中文 * @param chinese *            中文字符 * @return 验证成功返回true,验证失败返回false */ public static boolean checkChinese(String chinese) { String regex = "^[\u4E00-\u9FA5]+$"; return Pattern.matches(regex, chinese); } /** * 验证日期(年月日) * @param birthday *            日期,格式:1992-09-03,或1992.09.03 * @return 验证成功返回true,验证失败返回false */ public static boolean checkBirthday(String birthday) { String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; return Pattern.matches(regex, birthday); } /** * 验证URL地址 * @param url *            格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或 *            http://www.csdn.net:80 * @return 验证成功返回true,验证失败返回false */ public static boolean checkURL(String url) { String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?"; return Pattern.matches(regex, url); } /** * <pre> * 获取网址 URL 的一级域 * </pre> * @param url * @return */ public static String getDomain(String url) { Pattern p = Pattern.compile( "(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); // 获取完整的域名 // Pattern // p=Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", // Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(url); matcher.find(); return matcher.group(); } /** * 匹配中国邮政编码 * @param postcode *            邮政编码 * @return 验证成功返回true,验证失败返回false */ public static boolean checkPostcode(String postcode) { String regex = "[1-9]\\d{5}"; return Pattern.matches(regex, postcode); } /** * 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小) * @param ipAddress *            IPv4标准地址 * @return 验证成功返回true,验证失败返回false */ public static boolean checkIpAddress(String ipAddress) { String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; return Pattern.matches(regex, ipAddress); } /** * 正则表达式匹配多个结果 * @param input *            匹配文本 * @param regex *            正则表达式 * @return 匹配结果List集合 */ public static List<String> regexAll(String input, String regex) { List<String> strList = new ArrayList<String>(); Matcher matcher = matcherUtil(input, regex); while (matcher.find()) { strList.add(matcher.group(1)); } return strList; } /** * 正则表达式匹配单个结果 * @param input *            匹配文本 * @param regex *            正则表达式 * @return 匹配结果List集合 */ public static String regexFirst(String input, String regex) { Matcher matcher = matcherUtil(input, regex); if (matcher.find()) { return matcher.group(1); } return "";  } /** * 获取正则对象 * @param input *            匹配文本 * @param regex *            正则表达式 * @return Matcher对象 */ public static Matcher matcherUtil(String input, String regex) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); return matcher; } }

---第3步:测试

package com.yanshu.tools; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; public class pageNum { public static void main(String[] args) { // String url = "https://s.taobao.com/search?spm=a230r.1.0.0.3d2936f0doEGnW&q=女装外套冬&rs=up&rsclick=7&preq=女装2017新款潮&cps=yes&ppath=413:800000782;20000:123042686;122216562:47502"; String url = "http://api.s.m.taobao.com/search.json?m=shopitemsearch&sellerId=196993935&n=40&orderType=hotsell_desc&ajax=true"; // String url = "https://s.taobao.com/search?tab=all&ppath=20000:7043912&cat=54900006&q=FLAM&spma=1513693743"; String pageNum = HttpUtility.sendGet(url, null);   Map maps=(Map)JSON.parse(pageNum);   Map mapw=new HashMap<>();   Object key=null;   Object value=null;      Object proxystring=null;   for (Object map : maps.entrySet()){       key = ((Map.Entry)map).getKey();     value = ((Map.Entry)map).getValue();       mapw.put(key, value);       if( key =="totalPage"||key.equals("totalPage"))       {       proxystring=value;       }   }     System.out.println("-----"+proxystring); /*String JsonStr = RegexUtils2.regexFirst(pageNum, "g_page_config = (.*?)\\}\\};")+"}}"; // String JsonStr = RegexUtils2.regexFirst(pageNum, "jsonp873\\((.*?)\\}\\}\\);")+"}}"; Object mods = JSON.parseObject(JsonStr).get("mods"); Object sortbar = JSON.parseObject(mods.toString()).get("sortbar"); Object data = JSON.parseObject(sortbar.toString()).get("data"); Object pager = JSON.parseObject(data.toString()).get("pager"); Object totalPage = JSON.parseObject(pager.toString()).get("totalPage");*/ System.out.println(pageNum); } }

转载请注明原文地址: https://www.6miu.com/read-2400224.html

最新回复(0)