chongqing_2018_price_crawler.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. /**
  2. * @author vian
  3. * 重庆材料信息价爬虫
  4. * 由于headless chrome “puppeteer”占用资源比较大,且材料信息价的数据是ssr的静态内容,因此不需要使用puppeteer。
  5. * 数据获取使用cheerio(解析html,可用类jquery语法操作生成的数据)
  6. */
  7. module.exports = {
  8. crawlData,
  9. };
  10. const cheerio = require('cheerio');
  11. const axios = require('axios');
  12. const querystring = require('querystring');
  13. const uuidV1 = require('uuid/v1');
  14. const mongoose = require('mongoose');
  15. const { isDef } = require('../../../public/common_util');
  16. const compilationModel = mongoose.model('compilation');
  17. const priceInfoLibModel = mongoose.model('std_price_info_lib');
  18. const priceInfoClassModel = mongoose.model('std_price_info_class');
  19. const priceInfoItemModel = mongoose.model('std_price_info_items');
  20. const priceInfoAreaModel = mongoose.model('std_price_info_areas');
  21. const isDebug = true;
  22. function debugConsole(str, type = 'log') {
  23. if (isDebug) {
  24. console[type](str);
  25. }
  26. }
  27. // 页面类型
  28. const PageType = {
  29. GENERAL: '/Index.aspx',
  30. AREA: '/AreaIndex.aspx',
  31. MIXED: '/ReadyMixedIndex.aspx',
  32. };
  33. /**
  34. * 获取主要材料信息价格页面表单数据
  35. * @param {Object} $ - 页面内容
  36. * @param {Object} props - 提交属性
  37. */
  38. function getGeneralDataBody($, props) {
  39. const body = {
  40. __EVENTTARGET: props.eventTarget || '',
  41. __EVENTARGUMENT: '',
  42. __VIEWSTATE: $('#__VIEWSTATE').val(),
  43. __VIEWSTATEGENERATOR: $('#__VIEWSTATEGENERATOR').val(),
  44. ID_ucPrice$linkvv: props.period,
  45. ID_ucPrice$linkcategory: props.materialClass || '',
  46. ID_ucPrice$LinkValue: `${props.classID},${props.period},${props.materialClass || ''}`,
  47. ID_ucPrice$txtsonclass: `sonclass${props.classID}`,
  48. ID_ucPrice$txtfatherclass: $('#ID_ucPrice_txtfatherclass').val(),
  49. ID_ucPrice$txtClassId: props.classID || '',
  50. ID_ucPrice$ddlSearchYear: '请选择',
  51. ID_ucPrice$ddlSearchMonth: '请选择',
  52. ID_ucPrice$txtSearchCailiao: '',
  53. ID_ucPrice$UcPager1$listPage: props.page && String(props.page) || '1',
  54. };
  55. if (!props.eventTarget) {
  56. body.ID_ucPrice$btnLink = $('#ID_ucPrice_btnLink').val();
  57. }
  58. return body;
  59. }
  60. /**
  61. * 获取各区县地方材料工地价格页面表单数据
  62. * @param {Object} $ - 页面内容
  63. * @param {Object} props - 提交属性
  64. */
  65. function getAreaDataBody($, props) {
  66. if (!props || !Object.keys(props).length) {
  67. return {};
  68. }
  69. const body = {
  70. __EVENTTARGET: props.eventTarget || '',
  71. __EVENTARGUMENT: '',
  72. __VIEWSTATE: $('#__VIEWSTATE').val(),
  73. __VIEWSTATEGENERATOR: $('#__VIEWSTATEGENERATOR').val(),
  74. ID_ucAreaPrice$linkvv: props.period,
  75. ID_ucAreaPrice$LinkValue: '',
  76. ID_ucAreaPrice$dropArea: 'code',
  77. ID_ucAreaPrice$txtSearchCailiao: '',
  78. ID_ucAreaPrice$UcPager1$listPage: props.page && String(props.page) || '1',
  79. };
  80. if (!props.eventTarget) {
  81. body.ID_ucAreaPrice$btnAreaMaster = 'Button';
  82. }
  83. return body;
  84. }
  85. /**
  86. * 获取预拌砂浆信息价格页面表单数据
  87. * @param {Object} $ - 页面内容
  88. * @param {Object} props - 提交属性
  89. */
  90. function getMixedDataBody($, props) {
  91. if (!props || !Object.keys(props).length) {
  92. return {};
  93. }
  94. const body = {
  95. __EVENTTARGET: props.eventTarget || '',
  96. __EVENTARGUMENT: '',
  97. __VIEWSTATE: $('#__VIEWSTATE').val(),
  98. __VIEWSTATEGENERATOR: $('#__VIEWSTATEGENERATOR').val(),
  99. ID_ucReadyMixedPrice$linkvv: props.period,
  100. ID_ucReadyMixedPrice$LinkValue: '',
  101. ID_ucReadyMixedPrice$dropArea: 'code',
  102. ID_ucReadyMixedPrice$txtSearchCailiao: '',
  103. ID_ucReadyMixedPrice$UcPager1$listPage: props.page && String(props.page) || '1',
  104. };
  105. if (!props.eventTarget) {
  106. body.ID_ucReadyMixedPrice$btnAreaMaster = 'Button';
  107. }
  108. return body;
  109. }
  110. // 获取提交
  111. const TIME_OUT = 60000;
  112. // 创建axios实例
  113. const axiosInstance = axios.create({
  114. baseURL: 'http://www.cqsgczjxx.org/Jgxx/',
  115. timeout: TIME_OUT,
  116. /* proxy: {
  117. host: "127.0.0.1", port: "8888" // Fiddler抓包,需要打开Fiddler否则会报connect error
  118. }, */
  119. headers: {
  120. 'Cache-Control': 'max-age=0',
  121. 'Content-Type': 'application/x-www-form-urlencoded',
  122. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36',
  123. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  124. 'Accept-Encoding': 'gzip, deflate',
  125. 'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6',
  126. },
  127. responseType: 'document'
  128. });
  129. // 响应拦截器
  130. axiosInstance.interceptors.response.use(function (response) {
  131. return response;
  132. }, function (error) {
  133. // 对响应错误做点什么
  134. if (error.message.includes('timeout')) {
  135. return Promise.reject(`目标网络超时,请稍后再试。(${TIME_OUT}ms)`);
  136. } else {
  137. return Promise.reject(error);
  138. }
  139. });
  140. // 发起请求需要携带Cookie,否则一些请求会返回500错误(应该是网站的反爬措施)
  141. let curCookie = '';
  142. /**
  143. * 加载页面,获取可用类jquery操作的数据
  144. * @param {String} url - 拼接的url
  145. * @param {Object} body - 表单数据
  146. * @return {DOM-LIKE} - cheerio解析html得到的类dom数据
  147. */
  148. async function loadPage(url, body) {
  149. const config = {};
  150. if (curCookie) {
  151. config.headers = { Cookie: curCookie };
  152. }
  153. const rst = body ?
  154. await axiosInstance.post(url, querystring.stringify(body), config) :
  155. await axiosInstance.post(url, null, config);
  156. // 更新cookie
  157. const cookies = rst.headers['set-cookie'];
  158. if (Object.prototype.toString.call(cookies) === '[object Array]') {
  159. curCookie = cookies[0].split(';')[0];
  160. }
  161. return cheerio.load(rst.data);
  162. }
  163. const monthMap = {
  164. '1': '01月',
  165. '2': '02月',
  166. '3': '03月',
  167. '4': '04月',
  168. '5': '05月',
  169. '6': '06月',
  170. '7': '07月',
  171. '8': '08月',
  172. '9': '09月',
  173. '10': '10月',
  174. '11': '11月',
  175. '12': '12月',
  176. };
  177. /**
  178. * 获取期数数据
  179. * @param {String} from - 从哪一期开始 eg: 2020-01
  180. * @param {String} to - 从哪一期结束 eg: 2020-05
  181. * @param {Object} $index - cheerio加载的初始页面内容
  182. * @return {Array<object> || Null} eg: {period: '2020-05', uid: 'XCCXXXXX-XX'}
  183. */
  184. function getPeriodData(from, to, $index) {
  185. if (from > to) {
  186. return null;
  187. }
  188. const $period = $index('#PriceLMenu')
  189. // 根据区间获取期数列表
  190. const reg = /(\d+)-(\d+)/;
  191. const fromMatch = from.match(reg);
  192. const fromYear = +fromMatch[1];
  193. const fromMonth = +fromMatch[2];
  194. const toMatch = to.match(reg);
  195. const toYear = +toMatch[1];
  196. const toMonth = +toMatch[2];
  197. let curYear = fromYear;
  198. let curMonth = fromMonth;
  199. const list = [];
  200. while (curYear <= toYear && curMonth <= toMonth) {
  201. const uid = getPeriodUID(curYear, curMonth, $period);
  202. // 存在无效期数,直接返回空
  203. if (!uid) {
  204. return null;
  205. }
  206. list.push({
  207. period: `${curYear}年-${monthMap[curMonth]}`,
  208. uid
  209. });
  210. if (curMonth === 12) {
  211. curYear++;
  212. curMonth = 1;
  213. } else {
  214. curMonth++;
  215. }
  216. }
  217. return list;
  218. function getPeriodUID(year, month, $period) {
  219. const $year = $period.find('.MenuOneTitle').filter(function () {
  220. return $index(this).text() === `${year}年`;
  221. });
  222. if (!$year.length) {
  223. return null;
  224. }
  225. const $month = $year.parent().next().find('a').filter(function () {
  226. return $index(this).text() === `${month}月`;
  227. });
  228. if (!$month.length) {
  229. return null;
  230. }
  231. // 期数uid在onclick中,需要提取出来
  232. const onclickText = $month.attr('onclick').toString();
  233. const reg = /Onlink\('([^']+)'/;
  234. const matched = onclickText.match(reg);
  235. if (!matched || !matched[1]) {
  236. return null;
  237. }
  238. return matched[1];
  239. }
  240. }
  241. // 表格类型
  242. const TableType = {
  243. BUILDING: 1, // 主要材料中的建安工程材料和绿色
  244. GARDEN: 2, // 主要材料中的园林绿化
  245. ENERGY: 3, // 主要材料中的节能建筑工程材料
  246. AREA: 4, // 地区相关(各区县材料)
  247. MIXED: 5, // 地区相关(预拌砂浆)
  248. };
  249. /**
  250. * 爬取表格数据
  251. * @param {Object} $page - 页面内容
  252. * @param {Number} type - 表格类型
  253. * @return {Array<object>}
  254. */
  255. function crawlTableData($page, type) {
  256. switch (type) {
  257. case TableType.BUILDING:
  258. case TableType.ENERGY:
  259. return crawlNormalTable($page);
  260. case TableType.GARDEN:
  261. return crawlGardenTable($page);
  262. case TableType.AREA:
  263. return crawlAreaTable($page, '#ID_ucAreaPrice_gridView');
  264. case TableType.MIXED:
  265. return crawlAreaTable($page, '#ID_ucReadyMixedPrice_gridView');
  266. }
  267. return [];
  268. }
  269. /**
  270. * 爬取表格数据,表格列为:
  271. * 序号 | 材料名称 | 规格型号 | 单位 | 含税价(元) | 不含税价(元) | 备注
  272. * @param {Object} $page - 页面内容
  273. * @return {Array<object>}
  274. */
  275. function crawlNormalTable($page) {
  276. const colMap = {
  277. 0: 'name',
  278. 1: 'specs',
  279. 2: 'unit',
  280. 3: 'taxPrice',
  281. 4: 'noTaxPrice',
  282. 5: 'remark'
  283. };
  284. const data = [];
  285. let cur;
  286. const $tdList = $page('#ID_ucPrice_gridView').find('tr td span').filter(index => index % 7 !== 0); // 排除表头和序号列
  287. $tdList.each(function (index) {
  288. const col = index % 6;
  289. if (col === 0) {
  290. cur = {}
  291. }
  292. cur[colMap[col]] = $page(this).text();
  293. if (col === 5) {
  294. data.push(cur);
  295. }
  296. });
  297. debugConsole(data);
  298. return data;
  299. }
  300. /**
  301. * 爬取表格数据,表格列为:
  302. * 序号 | 科属 | 品名 | 高度(CM) | 干径(CM) | 冠径(CM) | 分枝高(CM) | 单位 | 含税价(元) | 不含税价(元) | 备注
  303. * @param {Object} $page - 页面内容
  304. * @return {Array<object>}
  305. */
  306. function crawlGardenTable($page) {
  307. const colMap = {
  308. 0: 'genera',
  309. 1: 'name',
  310. 2: 'height',
  311. 3: 'branchDiameter',
  312. 4: 'crownDiameter',
  313. 5: 'branchHeight',
  314. 6: 'unit',
  315. 7: 'taxPrice',
  316. 8: 'noTaxPrice',
  317. 9: 'remark',
  318. };
  319. const data = [];
  320. let cur;
  321. const $tdList = $page('#ID_ucPrice_gridView').find('tr td span').filter(index => index % 11 !== 0); // 排除表头和序号列
  322. $tdList.each(function (index) {
  323. const col = index % 10;
  324. if (col === 0) {
  325. cur = {}
  326. }
  327. cur[colMap[col]] = $page(this).text();
  328. if (col === 9) {
  329. data.push(cur);
  330. }
  331. });
  332. debugConsole(data);
  333. return data;
  334. }
  335. /**
  336. * 爬取表格数据,表格列为:
  337. * 序号 | 所属区县 | 材料名称 | 规格及型号 | 计量单位 | 含税价(元) | 不含税价(元)
  338. * @param {Object} $page - 页面内容
  339. * @param {String} viewSelector - 表格选择器(ID)
  340. * @return {Array<object>}
  341. */
  342. function crawlAreaTable($page, viewSelector) {
  343. const colMap = {
  344. 0: 'area',
  345. 1: 'name',
  346. 2: 'specs',
  347. 3: 'unit',
  348. 4: 'taxPrice',
  349. 5: 'noTaxPrice',
  350. };
  351. const data = [];
  352. let cur;
  353. const $tdList = $page(viewSelector).find('tr td span').filter(index => index % 7 !== 0); // 排除表头和序号列
  354. $tdList.each(function (index) {
  355. const col = index % 6;
  356. if (col === 0) {
  357. cur = {}
  358. }
  359. cur[colMap[col]] = $page(this).text();
  360. if (col === 5) {
  361. data.push(cur);
  362. }
  363. });
  364. debugConsole(data);
  365. return data;
  366. }
  367. // 事件触发类型
  368. const EventTarget = {
  369. GENERAL_NEXT: 'ID_ucPrice$UcPager1$btnNext',
  370. AREA_NEXT: 'ID_ucAreaPrice$UcPager1$btnNext',
  371. MIXED_NEXT: 'ID_ucReadyMixedPrice_UcPager1_btnNext',
  372. };
  373. /**
  374. * 爬取一页一页的表格数据
  375. * @param {Object} $index - 索引页面内容
  376. * @param {Object} props - 提交的表单内容
  377. * @param {String} pageType - 页面类型
  378. * @param {Number} tableType - 表格类型
  379. */
  380. async function crawlPagesData($index, props, pageType, tableType) {
  381. let body;
  382. let pageStateSelector;
  383. if (pageType === PageType.GENERAL) {
  384. body = getGeneralDataBody($index, props);
  385. pageStateSelector = '#ID_ucPrice_UcPager1_lbPage';
  386. } else if (pageType === PageType.AREA) {
  387. body = getAreaDataBody($index, props);
  388. pageStateSelector = '#ID_ucAreaPrice_UcPager1_lbPage';
  389. } else {
  390. body = getMixedDataBody($index, props);
  391. pageStateSelector = '#ID_ucReadyMixedPrice_UcPager1_lbPage';
  392. }
  393. const $firstPage = await loadPage(pageType, body);
  394. const rst = [];
  395. // 获取第一页数据
  396. rst.push(...crawlTableData($firstPage, tableType));
  397. if (!rst.length) { // 第一页都没数据,后续不需要操作了
  398. return rst;
  399. }
  400. // 获取除第一页的数据
  401. // 获取页码
  402. const pageState = $firstPage(pageStateSelector).text(); // eg: 1/10
  403. const totalPage = +pageState.split('/')[1];
  404. const asyncCount = 6; // 最高批量次数
  405. let curCount = 0;
  406. let task = [];
  407. for (let page = 1; page < totalPage; page++) {
  408. task.push(crawlPageData(page));
  409. curCount++;
  410. if (curCount === asyncCount) {
  411. const allData = await Promise.all(task);
  412. allData.forEach(data => rst.push(...data));
  413. curCount = 0;
  414. task = [];
  415. }
  416. }
  417. if (task.length) {
  418. const allData = await Promise.all(task);
  419. allData.forEach(data => rst.push(...data));
  420. }
  421. return rst;
  422. // 爬取页码数据
  423. async function crawlPageData(page) {
  424. const pageProps = { ...props, page };
  425. let body;
  426. if (pageType === PageType.GENERAL) {
  427. pageProps.eventTarget = EventTarget.GENERAL_NEXT;
  428. body = getGeneralDataBody($firstPage, pageProps);
  429. } else if (pageType === PageType.AREA) {
  430. pageProps.eventTarget = EventTarget.AREA_NEXT;
  431. body = getAreaDataBody($firstPage, pageProps);
  432. } else {
  433. pageProps.eventTarget = EventTarget.MIXED_NEXT;
  434. body = getMixedDataBody($firstPage, pageProps);
  435. }
  436. const $page = await loadPage(pageType, body);
  437. return crawlTableData($page, tableType);
  438. }
  439. }
  440. /**
  441. * 爬取建安工程材料和绿色、园林绿化工程材料、节能建筑工程材料
  442. * @param {String} period - 期数uid
  443. * @param {String} classID - 工程分类id
  444. * @param {Object} $index - 初始页面内容
  445. * @param {Number} type - 表格类型
  446. * @return {Array<object>} eg: [{ materialClass: '一、黑色及有色金属', items: [...] }]
  447. */
  448. async function crawlGeneralSubData(period, classID, $index, type) {
  449. const body = getGeneralDataBody($index, { period, classID });
  450. const $engineeringClassPage = await loadPage(PageType.GENERAL, body);
  451. const rst = [];
  452. if (type === TableType.BUILDING) {
  453. const classList = crawlMaterialClassList($index('#ID_ucPrice_CategoryLabel'));
  454. if (!classList.length) {
  455. throw '无法爬取到材料分类。';
  456. }
  457. const reg = /[一二三四五六七八九十]+、/;
  458. for (const materialClass of classList) {
  459. const obj = { materialClass: materialClass.replace(reg, ''), items: [] }; // 材料分类去除序号
  460. obj.items = await crawlPagesData($engineeringClassPage, { period, classID, materialClass }, PageType.GENERAL, type);
  461. rst.push(obj);
  462. }
  463. } else {
  464. const items = await crawlPagesData($engineeringClassPage, { period, classID, materialClass: '' }, PageType.GENERAL, type);
  465. rst.push(...items);
  466. }
  467. return rst;
  468. // 爬取材料分类表
  469. function crawlMaterialClassList($class) {
  470. const list = [];
  471. $class.find('a').each(function () {
  472. const text = $engineeringClassPage(this).text();
  473. list.push(text);
  474. });
  475. return list;
  476. }
  477. }
  478. /**
  479. * 爬取主要材料信息价格(这部分作为通用库)
  480. * @param {String} period - 期数uid
  481. * @param {Object} $index - 初始页面内容
  482. * @return {Object}
  483. */
  484. async function crawlGeneralData(period, $index) {
  485. const { building, garden, energy } = crawlClass($index('#ID_ucPrice_tabNewBar'));
  486. const rst = {};
  487. if (building) {
  488. rst.building = await crawlGeneralSubData(period, building, $index, TableType.BUILDING);
  489. }
  490. if (garden) {
  491. // 园林绿化工程材料下的数据所属分类为数据的"科属"列
  492. rst.garden = await crawlGeneralSubData(period, garden, $index, TableType.GARDEN);
  493. }
  494. if (energy) {
  495. // 绿色、节能建筑工程材料下的所有数据,所属分类均为“绿色、节能建筑工程材料”。
  496. rst.energy = await crawlGeneralSubData(period, energy, $index, TableType.ENERGY);
  497. }
  498. return rst;
  499. // 爬取工程分类
  500. function crawlClass($class) {
  501. // 工程分类
  502. let building; // 建安工程材料
  503. let garden; // 园林绿化工程材料
  504. let energy; // 绿色、节能建筑工程材料
  505. const reg = /OnClassson\('([^']+)'/;
  506. $class.find('a').each(function () {
  507. const text = $index(this).text();
  508. const onclickText = $index(this).attr('onclick').toString();
  509. const matched = onclickText.match(reg);
  510. if (!matched || !matched[1]) {
  511. throw '无法爬取到工程分类。';
  512. }
  513. if (text === '建安工程材料') {
  514. building = matched[1];
  515. } else if (text === '园林绿化工程材料') {
  516. garden = matched[1];
  517. } else if (text === '绿色、节能建筑工程材料') {
  518. energy = matched[1];
  519. }
  520. });
  521. return { building, garden, energy };
  522. }
  523. }
  524. /**
  525. * 爬取各区县地方材料工地价格
  526. * @param {String} period - 期数uid
  527. * @return {Array<object>}
  528. */
  529. async function crawlAreaData(period) {
  530. // 获取各区材料初始页
  531. const $index = await loadPage(PageType.AREA);
  532. // 获取地区材料
  533. return await crawlPagesData($index, { period }, PageType.AREA, TableType.AREA);
  534. }
  535. /**
  536. * 爬取预拌砂浆信息价格
  537. * @param {String} period - 期数uid
  538. * @return {Array<object>}
  539. */
  540. async function crawlMixedData(period) {
  541. // 获取各区材料初始页
  542. const $index = await loadPage(PageType.MIXED);
  543. // 获取地区材料
  544. return await crawlPagesData($index, { period }, PageType.MIXED, TableType.MIXED);
  545. }
  546. /**
  547. * 转换价格数据(一条源数据可能需要分割成多条数据)
  548. * @param {String} libID - 库ID
  549. * @param {String} classID - 所属分类ID
  550. * @param {String} period - 期数 eg:2020年01月
  551. * @param {String} areaID - 地区ID
  552. * @param {String} compilationID - 费用定额ID
  553. * @param {Array<object>} items - 爬取的信息价源数据
  554. * @param {Number} tableType - 表格类型
  555. * @return {Array<obejct>}
  556. */
  557. function transformPriceItems(libID, classID, period, areaID, compilationID, items, tableType) {
  558. const rst = [];
  559. if (tableType === TableType.GARDEN) {
  560. // 有的数据 高度(CM) | 干径(CM) | 冠径(CM) | 分枝高(CM) | 不含税价(元) = ‘’ | 14-17 | 大于400 | 200-300 | 430-780
  561. // 则此数据需要分为:
  562. // 1. { name: 名称-最低价, specs: 干径14-17CM 冠径大于400CM 分枝高200-300CM, noTaxPrice: 430 }
  563. // 2. { name: 名称-最高价, specs: 干径14-17CM 冠径大于400CM 分枝高200-300CM, noTaxPrice: 780 }
  564. const unit = 'CM';
  565. const duplicateReg = /-/;
  566. items.forEach(item => {
  567. // 拼接规格型号
  568. const specsList = [];
  569. if (item.height) {
  570. specsList.push(`高度${item.height}${unit}`);
  571. }
  572. if (item.branchDiameter) {
  573. specsList.push(`干径${item.branchDiameter}${unit}`);
  574. }
  575. if (item.crownDiameter) {
  576. specsList.push(`冠径${item.crownDiameter}${unit}`);
  577. }
  578. if (item.branchHeight) {
  579. specsList.push(`分枝高${item.branchHeight}${unit}`);
  580. }
  581. const specs = specsList.join(' ');
  582. // 分成最高低价最高价数据
  583. const isDuplicate = duplicateReg.test(item.taxPrice) || duplicateReg.test(item.noTaxPrice);
  584. if (isDuplicate) {
  585. const taxPriceList = item.taxPrice.split('-');
  586. const noTaxPriceList = item.noTaxPrice.split('-');
  587. const minItem = {
  588. ...item,
  589. name: `${item.name}-最低价`,
  590. specs,
  591. taxPrice: taxPriceList[0],
  592. noTaxPrice: noTaxPriceList[0]
  593. };
  594. const maxItem = {
  595. ...item,
  596. name: `${item.name}-最高价`,
  597. specs,
  598. taxPrice: taxPriceList[1] || '',
  599. noTaxPrice: noTaxPriceList[1] || ''
  600. };
  601. rst.push(transfromPriceItem(libID, classID, period, areaID, compilationID, minItem));
  602. rst.push(transfromPriceItem(libID, classID, period, areaID, compilationID, maxItem));
  603. } else {
  604. rst.push(transfromPriceItem(libID, classID, period, areaID, compilationID, item));
  605. }
  606. })
  607. } else {
  608. const duplicateReg = /\//;
  609. // 有的数据:规格型号 | 含税价(元) | 不含税价(元) = φ6(6.5)/φ8 HPB300 | 4030.00/3880.00 | 3566.37/3433.63,则这条数据需要分成两条数据
  610. items.forEach(item => {
  611. item.taxPrice = item.taxPrice === '-' ? '' : item.taxPrice;
  612. item.noTaxPrice = item.noTaxPrice === '-' ? '' : item.noTaxPrice;
  613. const isDuplicate = duplicateReg.test(item.taxPrice) || duplicateReg.test(item.noTaxPrice); // 以价格被分割,作为数据需要分割的判断
  614. if (isDuplicate) {
  615. // 提取规格型号分割部分和公共部分:Q390/Q420 δ=20-30 => Q390 δ=20-30; Q420 δ=20-30
  616. // 获取公共规格型号部分
  617. const commonReg = /\s+([^/]*)$/;
  618. const commonMatched = item.specs.match(commonReg);
  619. const commonSpecs = commonMatched && commonMatched[1] ? ' ' + commonMatched[1] : '';
  620. // 获取分割规格型号
  621. const specsList = item.specs
  622. .replace(commonReg, '')
  623. .split('/');
  624. const taxPriceList = item.taxPrice.split('/');
  625. const noTaxPriceList = item.noTaxPrice.split('/');
  626. specsList.forEach((specs, index) => {
  627. const newItem = {
  628. ...item,
  629. specs: `${specs}${commonSpecs}`,
  630. taxPrice: taxPriceList[index] || taxPriceList[0],
  631. noTaxPrice: noTaxPriceList[index] || noTaxPriceList[0]
  632. };
  633. if (areaID) {
  634. newItem.areaID = areaID;
  635. }
  636. rst.push(transfromPriceItem(libID, classID, period, areaID, compilationID, newItem));
  637. });
  638. } else {
  639. rst.push(transfromPriceItem(libID, classID, period, areaID, compilationID, item));
  640. }
  641. });
  642. }
  643. return rst;
  644. }
  645. // 转换单条的价格数据
  646. function transfromPriceItem(libID, classID, period, areaID, compilationID, item) {
  647. // 源数据中的规格型号存在多个无意义的空格,合并为一个
  648. const reg = /\s{2,}/g;
  649. item.specs = item.specs ? item.specs.replace(reg, ' ') : '';
  650. return {
  651. ID: uuidV1(),
  652. libID,
  653. classID,
  654. code: '',
  655. name: item.name,
  656. specs: item.specs,
  657. unit: item.unit,
  658. taxPrice: item.taxPrice,
  659. noTaxPrice: item.noTaxPrice,
  660. remark: item.remark || '',
  661. // 以下冗余数据为方便前台信息价功能处理
  662. period,
  663. areaID,
  664. compilationID,
  665. }
  666. }
  667. /**
  668. * 转换主要材料
  669. * @param {String} period - 日期: 2020年01月
  670. * @param {String} compilationID - 费用定额ID
  671. * @param {Object} generalData - 主要材料{ building, garden, energy }
  672. * @return {Object} { libData, classData, priceData, compilationAreas }
  673. */
  674. async function transfromGeneralData(period, compilationID, generalData) {
  675. const area = '通用';
  676. // 爬取数据的时候,地区数据先匹配名称,如果费用定额已有此地区,不新增
  677. const matchedArea = await priceInfoAreaModel.findOne({ compilationID, name: area }).lean();
  678. const areaID = matchedArea && matchedArea.ID || uuidV1();
  679. const compilationAreas = [];
  680. const libData = {
  681. ID: uuidV1(),
  682. name: `信息价(${period})`,
  683. period,
  684. areas: [],
  685. compilationID,
  686. createDate: Date.now(),
  687. };
  688. const classData = [];
  689. let curClassIndex = 0;
  690. const priceData = [];
  691. const { building, garden, energy } = generalData;
  692. handleClassAndItems(building, TableType.BUILDING);
  693. // 园林分类数据为:苗木-科属(genera)
  694. const gardenRoot = { materialClass: '苗木', treeData: { ID: uuidV1(), ParentID: '-1' } };
  695. const gardenData = [gardenRoot];
  696. garden.forEach(item => {
  697. const pre = gardenData[gardenData.length - 1];
  698. if (item.genera !== pre.materialClass) {
  699. gardenData.push({ materialClass: item.genera, treeData: { ParentID: gardenRoot.treeData.ID }, items: [item] });
  700. } else {
  701. pre.items.push(item);
  702. }
  703. });
  704. handleClassAndItems(gardenData, TableType.GARDEN)
  705. // 绿色节能分类数据:绿色、节能建筑工程材料
  706. const energyData = [{ materialClass: '绿色、节能建筑工程材料', items: energy }];
  707. handleClassAndItems(energyData, TableType.ENERGY);
  708. // 有数据才将地区push入areas中(费用定额共用)
  709. if ((classData.length || priceData.length) && !matchedArea) {
  710. compilationAreas.push({ compilationID, ID: areaID, name: area })
  711. }
  712. return { libData, classData, priceData, compilationAreas };
  713. function handleClassAndItems(sourceData, tableType) {
  714. if (!sourceData) {
  715. return;
  716. }
  717. sourceData.forEach(({ materialClass, treeData, items }) => {
  718. const classItem = {
  719. ID: treeData && treeData.ID || uuidV1(),
  720. ParentID: treeData && treeData.ParentID || '-1',
  721. NextSiblingID: treeData && treeData.NextSiblingID || '-1',
  722. name: materialClass,
  723. libID: libData.ID,
  724. areaID,
  725. };
  726. // 设置上一个节点数据的NextID
  727. let count = 1;
  728. let pre = classData[curClassIndex - 1];
  729. while (pre && pre.ParentID !== classItem.ParentID) {
  730. count++;
  731. pre = classData[curClassIndex - count];
  732. }
  733. if (pre && pre.ParentID === classItem.ParentID) {
  734. pre.NextSiblingID = classItem.ID;
  735. }
  736. curClassIndex++;
  737. classData.push(classItem);
  738. // 转换价格数据
  739. if (items && items.length) {
  740. const newItems = transformPriceItems(libData.ID, classItem.ID, period, areaID, compilationID, items, tableType);
  741. newItems.forEach(item => priceData.push(item));
  742. }
  743. });
  744. }
  745. }
  746. /**
  747. * 转换跟地区相关的数据
  748. * 地区作为期数库的子项
  749. * @param {String} period - 日期: 2020年01月
  750. * @param {String} compilationID - 费用定额ID
  751. * @param {String} className - 分类名称
  752. * @param {Object} libData - 当前期数库数据
  753. * @param {Array<object>} areaData - 各区县地方材料工地价格
  754. * @param {Array<object>} mixedData - 预拌砂浆信息价格
  755. * @return {Object}
  756. */
  757. async function transformAreaData(period, compilationID, libData, areaData, mixedData) {
  758. // 根据地区进行分类
  759. const data = [];
  760. const hashMap = {}; // 保证地区顺序跟网页爬取数据的顺序一致。(object for in无法保证顺序)
  761. function hash(area) {
  762. if (!isDef(hashMap[area])) {
  763. hashMap[area] = Object.keys(hashMap).length
  764. }
  765. return hashMap[area];
  766. }
  767. const areaClass = '地方材料信息价';
  768. const mixedClass = '预拌商品砂浆';
  769. function buildData(sourceData) {
  770. sourceData.forEach(item => {
  771. const idx = hash(item.area);
  772. if (!data[idx]) {
  773. data[idx] = { area: item.area, subData: [] };
  774. }
  775. if (sourceData === areaData) {
  776. // 存在地区数据,需要生成分类“地方材料信息价”
  777. if (!data[idx].subData[0]) {
  778. data[idx].subData[0] = { className: areaClass, items: [] };
  779. }
  780. data[idx].subData[0].items.push(item);
  781. } else if (sourceData === mixedData) {
  782. // 存在地区数据,需要生成分类“地方材料信息价”
  783. if (!data[idx].subData[1]) {
  784. data[idx].subData[1] = { className: mixedClass, items: [] };
  785. }
  786. data[idx].subData[1].items.push(item);
  787. }
  788. });
  789. }
  790. buildData(areaData);
  791. buildData(mixedData);
  792. const compilationAreas = [];
  793. const classData = [];
  794. const priceData = [];
  795. for (const { area, subData } of data) {
  796. const matchedArea = await priceInfoAreaModel.findOne({ compilationID, name: area }).lean();
  797. const areaID = matchedArea && matchedArea.ID || uuidV1();
  798. if (!matchedArea) {
  799. compilationAreas.push({ compilationID, ID: areaID, name: area });
  800. }
  801. let preClass;
  802. subData.forEach(subItem => {
  803. if (!subItem) {
  804. return;
  805. }
  806. const { className, items } = subItem;
  807. const classItem = {
  808. ID: uuidV1(),
  809. ParentID: '-1',
  810. NextSiblingID: '-1',
  811. name: className,
  812. libID: libData.ID,
  813. areaID,
  814. };
  815. classData.push(classItem);
  816. if (preClass) {
  817. preClass.NextSiblingID = classItem.ID;
  818. }
  819. preClass = classItem;
  820. const newItems = transformPriceItems(libData.ID, classItem.ID, period, areaID, compilationID, items, TableType.AREA);
  821. newItems.forEach(item => priceData.push(item));
  822. });
  823. }
  824. return { classData, priceData, compilationAreas };
  825. }
  826. /**
  827. * 数据入库
  828. * 生成一个通用库及各地区
  829. * @param {String} period 期数 eg: '2020年05月'
  830. * @param {Object} generalData - 主要材料{ building, garden, energy }
  831. * @param {Array<object>} areaData - 各地区材料
  832. * @param {Array<object>} mixedData - 各地区预拌砂浆
  833. */
  834. async function save(period, generalData, areaData, mixedData) {
  835. const overWriteUrl = '/web/over_write/js/chongqing_2018.js';
  836. const compilation = await compilationModel.findOne({ overWriteUrl }, '_id').lean();
  837. if (!compilation) {
  838. throw '没有找到正确配置overWriteUrl的费用定额。';
  839. }
  840. const compilationID = compilation._id;
  841. // 转换数据
  842. const generalSaveData = await transfromGeneralData(period, compilationID, generalData);
  843. const libData = generalSaveData.libData;
  844. const areaSaveData = await transformAreaData(period, compilationID, libData, areaData, mixedData);
  845. // 入库
  846. const classData = [...generalSaveData.classData, ...areaSaveData.classData];
  847. const priceData = [...generalSaveData.priceData, ...areaSaveData.priceData];
  848. const compilationAreas = [...generalSaveData.compilationAreas, ...areaSaveData.compilationAreas]
  849. // 删除已有的相同期数数据
  850. const originalLibs = await priceInfoLibModel.find({ period }, '-_id ID').lean();
  851. const originalLibIDList = originalLibs.reduce((acc, cur) => {
  852. acc.push(cur.ID);
  853. return acc;
  854. }, []);
  855. if (originalLibIDList.length) {
  856. await priceInfoItemModel.deleteMany({ period });
  857. await priceInfoClassModel.deleteMany({ libID: { $in: originalLibIDList } });
  858. await priceInfoLibModel.deleteMany({ period });
  859. }
  860. // 插入数据
  861. if (priceData.length) {
  862. await priceInfoItemModel.insertMany(priceData);
  863. }
  864. if (classData.length) {
  865. await priceInfoClassModel.insertMany(classData);
  866. }
  867. if (libData) {
  868. await priceInfoLibModel.insertMany([libData]);
  869. }
  870. if (compilationAreas) {
  871. await priceInfoAreaModel.insertMany(compilationAreas);
  872. }
  873. }
  874. /**
  875. * 爬取数据
  876. * @param {String} from - 从哪一期开始 eg: 2020-01
  877. * @param {String} to - 从哪一期结束 eg: 2020-05
  878. * @return {Object}
  879. */
  880. async function crawlData(from, to) {
  881. let curPeriod;
  882. try {
  883. const $index = await loadPage(PageType.GENERAL);
  884. const periodData = getPeriodData(from, to, $index);
  885. if (!periodData) {
  886. throw '无效的期数区间。';
  887. }
  888. // 一期一期爬取数据
  889. debugConsole('allTime', 'time');
  890. for (const periodItem of periodData) {
  891. debugConsole('peroidTime', 'time');
  892. // 爬取主要材料信息价格
  893. const generalData = await crawlGeneralData(periodItem.uid, $index); // 初始页面就是主要材料信息价的页面
  894. // 爬取各区县地方材料工地价格
  895. const areaData = await crawlAreaData(periodItem.uid);
  896. // 爬取预拌砂浆信息价格
  897. const mixedData = await crawlMixedData(periodItem.uid);
  898. // 转换数据并入库
  899. await save(periodItem.period, generalData, areaData, mixedData);
  900. curPeriod = periodItem.period;
  901. debugConsole('peroidTime', 'timeEnd');
  902. }
  903. debugConsole('allTime', 'timeEnd');
  904. } catch (err) {
  905. console.log(err);
  906. // 错误时提示已经成功爬取的期数
  907. let errTip = '';
  908. if (curPeriod) {
  909. errTip += `\n成功爬取期数为:${from}到${curPeriod}`;
  910. }
  911. const errStr = String(err) + errTip;
  912. console.log(`err`);
  913. console.log(errStr);
  914. throw errStr;
  915. }
  916. }