chongqing_2018_price_crawler.js 33 KB

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