Application5.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package space.anyi;
  2. import org.apache.http.NameValuePair;
  3. import org.apache.http.client.config.RequestConfig;
  4. import org.apache.http.client.entity.UrlEncodedFormEntity;
  5. import org.apache.http.client.methods.CloseableHttpResponse;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.message.BasicNameValuePair;
  11. import org.apache.http.util.EntityUtils;
  12. import org.jsoup.Jsoup;
  13. import org.jsoup.nodes.Document;
  14. import org.jsoup.nodes.Element;
  15. import org.jsoup.select.Elements;
  16. import java.sql.Connection;
  17. import java.sql.Date;
  18. import java.sql.PreparedStatement;
  19. import java.sql.ResultSet;
  20. import java.time.LocalDate;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import java.util.Objects;
  24. import java.util.regex.Matcher;
  25. import java.util.regex.Pattern;
  26. public class Application5 {
  27. static String indexUrl = "http://ztb.chinays.gov.cn/ceinwz/WebInfo_List.aspx?newsid=81&jsgc=01100000&zfcg=&tdjy=&cqjy=&qtjy=&PubDateSort=1&ShowPre=1&CbsZgys=0&zbfs=&qxxx=0&showqxname=0&NewsShowPre=1&wsjj=0&showCgr=0&ShowOverDate=0&showdate=1&FromUrl=zbgg";
  28. static String baseUrl = "https://www.tjdl.gov.cn";
  29. public static Pattern pattern = Pattern.compile("(\\d{4})(年|/|-|\\.)(\\d{1,2})(月|/|-|\\.)(\\d{1,2})");
  30. static MyDao myDao = new MyDao();
  31. public static void main(String[] args) throws Exception {
  32. getList();
  33. }
  34. // static int total = 1;
  35. // static int index = 0;
  36. static int count = 0;
  37. static String __EVENTVALIDATION = "";
  38. static String __VIEWSTATEGENERATOR = "";
  39. static String ctl00_myTreeView_ExpandState = "ennnnn";
  40. static String __VIEWSTATE = "";
  41. public static void getList() throws Exception {
  42. while (true){
  43. //列表url构建
  44. String listUrl = indexUrl;
  45. System.out.println(listUrl);
  46. //采集列表页
  47. String res;
  48. if (count == 0) {
  49. res = doGet(listUrl);
  50. }else {
  51. res = doPost(listUrl);
  52. }
  53. //采集总页数
  54. Document doc = Jsoup.parse(res);
  55. //有没有下一页
  56. __EVENTVALIDATION = doc.select("#__EVENTVALIDATION").first().val();
  57. __VIEWSTATEGENERATOR = doc.select("#__VIEWSTATEGENERATOR").first().val();
  58. // ctl00_myTreeView_ExpandState = doc.select("#ctl00_myTreeView_ExpandState").first().val();
  59. __VIEWSTATE = doc.select("#__VIEWSTATE").first().val();
  60. Element nextPage = doc.getElementById("ctl00_ContentPlaceHolder1_LinkButtonNextPage");
  61. //列表
  62. Elements eachTags = doc.select("table.myGVClass tr:has(a)");
  63. if (eachTags != null) {
  64. if (eachTags.size() > 0) {
  65. for (Element eachTag : eachTags) {
  66. count++;
  67. //解析详情页url
  68. String href = eachTag.select("a").first().attr("href");
  69. String link = "";
  70. String currentUrl = listUrl;
  71. link = urlClean(href,baseUrl,currentUrl);
  72. String title = eachTag.select("a").first().text().trim();
  73. System.out.println(title);
  74. System.out.println(link);
  75. //数据库是否已存在
  76. String querySql = "select DETAIL_LINK from XIN_XI_INFO_TEST where DETAIL_LINK = ?";
  77. try(Connection connection = MyDao.getConnection();
  78. PreparedStatement prepareStatement = connection.prepareStatement(querySql);){
  79. prepareStatement.setString(1,link);
  80. ResultSet resultSet = prepareStatement.executeQuery();
  81. if (resultSet.next()) {
  82. System.out.println("跳过" + link);
  83. resultSet.close();
  84. continue;
  85. }
  86. resultSet.close();
  87. }
  88. //采集详情页
  89. String detail = doGet(link);
  90. detail = detail.replace("display:none;", "");
  91. Document document = Jsoup.parse(detail);
  92. //#form1 > div:nth-child(3) > table > tbody > tr:nth-child(1) > td > table
  93. Element content = document.getElementById("form1");
  94. if (Objects.isNull(content)) {
  95. content = document.select("#aspnetForm > div:nth-child(3) > table:nth-child(4) > tbody:nth-child(2) > tr > td:nth-child(3) > div > table").first();
  96. }
  97. //文件url清洗
  98. Elements elements = content.select("a.lan");
  99. if (Objects.nonNull(elements) && elements.size() > 0) {
  100. elements.remove();
  101. }
  102. Elements as = content.select("a");
  103. for (Element a : as) {
  104. href = a.attr("href");
  105. href = urlClean(href,baseUrl,link);
  106. a.attr("href", href);
  107. }
  108. //图片url清洗
  109. Elements imgs = content.select("img");
  110. for (Element img : imgs) {
  111. String src = img.attr("src");
  112. src = urlClean(src,baseUrl,link);
  113. img.attr("src", src);
  114. }
  115. //正文清洗
  116. // Element frmBestwordHtml = content.getElementById("frmBestwordHtml");
  117. // if (Objects.nonNull(frmBestwordHtml)) {
  118. // String src = frmBestwordHtml.attr("src");
  119. // src = urlClean(src, baseUrl, link);
  120. // frmBestwordHtml.attr("src", src);
  121. // try {
  122. // res = doGet(src);
  123. // Element element = Jsoup.parse(res);
  124. // frmBestwordHtml.replaceWith(element);
  125. // } catch (Exception e) {
  126. // throw new RuntimeException(e);
  127. // }
  128. // }
  129. //save
  130. //字段:ID,SOURCE_NAME(网站名称),DETAIL_LINK(详情链接),DETAIL_TITLE(详情标题),DETAIL_CONTENT(正文HTML),PAGE_TIME(列表时间),CREATE_TIME(创建时间),LIST_TITLE(列表标题),CREATE_BY(创建者名称)
  131. String SOURCE_NAME = "英山县公共资源交易中心-英山县政府采购中心";
  132. String DETAIL_LINK = link;
  133. Element titleElement = content.getElementById("lblXmmc");
  134. if (Objects.isNull(titleElement)) {
  135. titleElement = content.getElementById("ctl00_ContentPlaceHolder1_TitleLabel");
  136. }
  137. String DETAIL_TITLE = titleElement.text().trim();
  138. String DETAIL_CONTENT = content.toString();
  139. //有可能出現 ”2026-10-14 [正在进行]“
  140. String dateStr = eachTag.select("td.fFbDate").first().text().trim();
  141. Matcher matcher = pattern.matcher(dateStr);
  142. if (matcher.find()) {
  143. String month = matcher.group(3).length() == 2 ? matcher.group(3) : "0" + matcher.group(3);
  144. String day = matcher.group(5).length() == 2 ? matcher.group(5) : "0" + matcher.group(5);
  145. dateStr = matcher.group(1) + "-" + month + "-" + day;
  146. }
  147. LocalDate PAGE_TIME = LocalDate.parse(dateStr);
  148. LocalDate CREATE_TIME = LocalDate.now();
  149. String LIST_TITLE = title;
  150. String CREATE_BY = "黄略";
  151. String sql = "insert into " + MyDao.TABLE_NAME +"(SOURCE_NAME,DETAIL_LINK,DETAIL_TITLE,DETAIL_CONTENT,PAGE_TIME,CREATE_TIME,LIST_TITLE,CREATE_BY) VALUES (?,?,?,?,?,?,?,?)";
  152. try(Connection connection = MyDao.getConnection();
  153. PreparedStatement preparedStatement = connection.prepareStatement(sql);){
  154. preparedStatement.setString(1, SOURCE_NAME);
  155. preparedStatement.setString(2, DETAIL_LINK);
  156. preparedStatement.setString(3, DETAIL_TITLE);
  157. preparedStatement.setString(4, DETAIL_CONTENT);
  158. preparedStatement.setDate(5, Date.valueOf(PAGE_TIME)); // LocalDate -> java.sql.Date
  159. preparedStatement.setDate(6, Date.valueOf(CREATE_TIME));
  160. preparedStatement.setString(7, LIST_TITLE);
  161. preparedStatement.setString(8, CREATE_BY);
  162. preparedStatement.executeUpdate();
  163. }
  164. }
  165. }
  166. }
  167. if (Objects.isNull(nextPage)) {
  168. break;
  169. }
  170. }
  171. System.out.println(count);
  172. }
  173. public static String doGet(String url) throws Exception {
  174. String result = "";
  175. CloseableHttpClient httpClient = HttpClients.createDefault();
  176. HttpGet httpGet = new HttpGet(url);
  177. RequestConfig requestConfig = RequestConfig.custom()
  178. .setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000)
  179. .build();
  180. httpGet.setConfig(requestConfig);
  181. CloseableHttpResponse response = null;
  182. try {
  183. response = httpClient.execute(httpGet);
  184. if (response.getStatusLine().getStatusCode() == 200) {
  185. String content = EntityUtils.toString(response.getEntity(), "UTF-8");
  186. result = content;
  187. }
  188. } finally {
  189. if (response != null) {
  190. response.close();
  191. }
  192. httpClient.hashCode();
  193. }
  194. return result;
  195. }
  196. public static String doPost(String path) throws Exception {
  197. String result = "";
  198. CloseableHttpClient httpclient = HttpClients.createDefault();
  199. // 创建http POST请求
  200. HttpPost httpPost = new HttpPost(path);
  201. RequestConfig requestConfig = RequestConfig.custom()
  202. .setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000)
  203. .build();
  204. httpPost.setConfig(requestConfig);
  205. List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
  206. parameters.add(new BasicNameValuePair("__EVENTVALIDATION",__EVENTVALIDATION));
  207. parameters.add(new BasicNameValuePair("__VIEWSTATEGENERATOR",__VIEWSTATEGENERATOR));
  208. parameters.add(new BasicNameValuePair("ctl00_myTreeView_ExpandState",ctl00_myTreeView_ExpandState));
  209. parameters.add(new BasicNameValuePair("__VIEWSTATE",__VIEWSTATE));
  210. parameters.add(new BasicNameValuePair("__EVENTTARGET","ctl00$ContentPlaceHolder1$LinkButtonNextPage"));
  211. // 构造一个form表单式的实体
  212. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
  213. // 将请求实体设置到httpPost对象中
  214. httpPost.setEntity(formEntity);
  215. httpPost.setHeader("User-Agent",
  216. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36");
  217. CloseableHttpResponse response = null;
  218. try {
  219. response = httpclient.execute(httpPost);
  220. if (response.getStatusLine().getStatusCode() == 200) {
  221. String content = EntityUtils.toString(response.getEntity(), "UTF-8");
  222. return content;
  223. }
  224. } finally {
  225. if (response != null) {
  226. response.close();
  227. }
  228. httpclient.close();
  229. }
  230. return result;
  231. }
  232. public static String urlClean(String url,String baseUrl,String currentUrl){
  233. String result = "";
  234. if (url.startsWith("/")) {
  235. //根路径开始
  236. result = baseUrl + url;
  237. }else if (url.startsWith("./")){
  238. //当前同级目录
  239. result = currentUrl.substring(0, currentUrl.lastIndexOf("/")) + url.substring(url.indexOf("./") + 1);
  240. }else if (url.startsWith("../")){
  241. //多级目录,取最后的uri拼接到baseUrl,等价于所有 "../" 替换成 "/"
  242. result = baseUrl + url.substring(url.lastIndexOf("../") + 2);
  243. }else {
  244. //等价于当前目录
  245. result = currentUrl.substring(0,currentUrl.lastIndexOf("/") + 1) + url;
  246. }
  247. return result;
  248. }
  249. }