this is based on calsyslab project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

302 lines
12 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. import glob
  3. import os
  4. import codecs
  5. import shutil
  6. from MarketPlaces.DB_Connection.db_connection import *
  7. from MarketPlaces.DarkFox.parser import *
  8. from MarketPlaces.Tor2door.parser import *
  9. from MarketPlaces.Classifier.classify_product import predict
  10. def mergePages(rmm, rec):
  11. # key = u"Pr:" + rec[1].upper() + u" Vendor:" + rec[18].upper()
  12. # key = rec[23]
  13. print("----------------- Matched: " + rec[1] + "--------------------")
  14. if rec[1] == "-1": # name_vendor
  15. rec[1] = rmm[0]
  16. if rec[2] == "-1": # rating_vendor
  17. rec[2] = rmm[1]
  18. if rec[3] == "-1": # success_vendor
  19. rec[3] = rmm[2]
  20. if rec[4] == "-1": # name_item
  21. rec[4] = rmm[3]
  22. if rec[5] == "-1": # description_item
  23. rec[5] = rmm[4]
  24. if rec[6] == "-1": # cve_item
  25. rec[6] = rmm[5]
  26. if rec[7] == "-1": # ms_item
  27. rec[7] = rmm[6]
  28. if rec[8] == "-1": # category_item
  29. rec[8] = rmm[7]
  30. if rec[9] == "-1": # views_item
  31. rec[9] = rmm[8]
  32. if rec[10] == "-1": # reviews_item
  33. rec[10] = rmm[9]
  34. if rec[11] == "-1": # rating_item
  35. rec[11] = rmm[10]
  36. if rec[12] == "-1": # adddate_item
  37. rec[12] = rmm[11]
  38. if rec[13] == "-1": # btc_item
  39. rec[13] = rmm[12]
  40. if rec[14] == "-1": # usd_item
  41. rec[14] = rmm[13]
  42. if rec[15] == "-1": # euro_item
  43. rec[15] = rmm[14]
  44. if rec[16] == "-1": # quantitysold_item
  45. rec[16] = rmm[15]
  46. if rec[17] == "-1": # quantityleft_item
  47. rec[17] = rmm[16]
  48. if rec[18] == "-1": # shippedfrom_item
  49. rec[18] = rmm[17]
  50. if rec[19] == "-1": # shippedto_item
  51. rec[19] = rmm[18]
  52. return rec
  53. def persist_data(url, row, cur):
  54. marketPlace = create_marketPlace(cur, row, url)
  55. vendor = create_vendor(cur, row, marketPlace)
  56. create_items(cur, row, marketPlace, vendor)
  57. def new_parse(marketPlace, url, createLog):
  58. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  59. print("Parsing the " + marketPlace + " marketplace and conduct data classification to store the information in the database.")
  60. # ini = time.time()
  61. # Connecting to the database
  62. con = connectDataBase()
  63. cur = con.cursor()
  64. # Creating the tables (The database should be created manually)
  65. create_database(cur, con)
  66. nError = 0
  67. lines = [] # listing pages
  68. lns = [] # description pages
  69. detPage = {}
  70. #Creating the log file for each Market Place
  71. if createLog:
  72. if not os.path.exists("./" + marketPlace + "/Logs/" + marketPlace + "_" + CURRENT_DATE + ".log"):
  73. logFile = open("./" + marketPlace + "/Logs/" + marketPlace + "_" + CURRENT_DATE + ".log", "w")
  74. else:
  75. print("Files of the date " + CURRENT_DATE + " from the Market Place " + marketPlace +
  76. " were already read. Delete the referent information in the Data Base and also delete the log file"
  77. " in the _Logs folder to read files from this Market Place of this date again.")
  78. raise SystemExit
  79. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + marketPlace + "/HTML_Pages")
  80. # Reading the Listing Html Pages
  81. for fileListing in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html')):
  82. lines.append(fileListing)
  83. # Reading the Description Html Pages
  84. for fileDescription in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", '*.html')):
  85. lns.append(fileDescription)
  86. # Parsing the Description Pages and put the tag's content into a dictionary (Hash table)
  87. for index, line2 in enumerate(lns):
  88. print("Reading description folder of '" + marketPlace + "', file '" + os.path.basename(line2) + "', index= " + str(index + 1) + " ... " + str(len(lns)))
  89. try:
  90. html = codecs.open(line2.strip('\n'), encoding='utf8')
  91. soup = BeautifulSoup(html, "html.parser")
  92. html.close()
  93. except:
  94. try:
  95. html = open(line2.strip('\n'))
  96. soup = BeautifulSoup(html, "html.parser")
  97. html.close()
  98. except:
  99. nError += 1
  100. print("There was a problem to read the file " + line2 + " in the Description section!")
  101. if createLog:
  102. logFile.write(str(nError) + ". There was a problem to read the file " + line2 + " in the Description section.\n")
  103. continue
  104. try:
  105. if marketPlace == "DarkFox":
  106. rmm = darkfox_description_parser(soup)
  107. elif marketPlace == "Tor2door":
  108. rmm = tor2door_description_parser(soup)
  109. # key = u"Pr:" + rmm[0].upper()[:desc_lim1] + u" Vendor:" + rmm[13].upper()[:desc_lim2]
  110. key = u"Url:" + os.path.basename(line2).replace(".html", "")
  111. # save file address with description record in memory
  112. detPage[key] = {'rmm': rmm, 'filename': os.path.basename(line2)}
  113. except:
  114. nError += 1
  115. print("There was a problem to parse the file " + line2 + " in the Description section!")
  116. if createLog:
  117. logFile.write(str(nError) + ". There was a problem to parse the file " + line2 + " in the Description section.\n")
  118. # Parsing the Listing Pages and put the tag's content into a list
  119. for index, line1 in enumerate(lines):
  120. print("Reading listing folder of '" + marketPlace + "', file '" + os.path.basename(line1) + "', index= " + str(index + 1) + " ... " + str(len(lines)))
  121. readError = False
  122. try:
  123. html = codecs.open(line1.strip('\n'), encoding='utf8')
  124. soup = BeautifulSoup(html, "html.parser")
  125. html.close()
  126. except:
  127. try:
  128. html = open(line1.strip('\n'))
  129. soup = BeautifulSoup(html, "html.parser")
  130. html.close()
  131. except:
  132. nError += 1
  133. print("There was a problem to read the file " + line1 + " in the Listing section!")
  134. if createLog:
  135. logFile.write(str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  136. readError = True
  137. if not readError:
  138. parseError = False
  139. try:
  140. if marketPlace == "DarkFox":
  141. rw = darkfox_listing_parser(soup)
  142. elif marketPlace == "Tor2door":
  143. rw = tor2door_listing_parser(soup)
  144. else:
  145. parseError = True
  146. except:
  147. nError += 1
  148. print("There was a problem to parse the file " + line1 + " in the listing section!")
  149. if createLog:
  150. logFile.write(
  151. str(nError) + ". There was a problem to parse the file " + line1 + " in the Listing section.\n")
  152. parseError = True
  153. if not parseError:
  154. persistError = False
  155. moveError = False
  156. num_in_db = 0
  157. num_persisted_moved = 0
  158. for rec in rw:
  159. rec = rec.split(',')
  160. # if len(detPage) > 0: #It was created here just because Zeroday Market does not have Description Pages
  161. # key = rec[23]
  162. # key = u"Pr:" + rec[1].upper()[:list_lim1] + u" Vendor:" + rec[18].upper()[:list_lim2]
  163. key = u"Url:" + cleanLink(rec[20])
  164. # if the associated description page is parsed
  165. if key in detPage:
  166. # rec = mergePages(detPage, rec)
  167. # Combining the information from Listing and Description Pages
  168. rmm = detPage[key]['rmm']
  169. rec = mergePages(rmm, rec)
  170. # Append to the list the classification of the product
  171. # rec.append(str(predict(rec[1], rec[5], language='markets')))
  172. rec.append(str(predict(rec[4], rec[5], language='sup_english')))
  173. # Persisting the information in the database
  174. try:
  175. persist_data(url, tuple(rec), cur)
  176. con.commit()
  177. except:
  178. trace = traceback.format_exc()
  179. if trace.find("already exists") == -1:
  180. nError += 1
  181. print("There was a problem to persist the file " + detPage[key]['filename'] + " in the database!")
  182. if createLog:
  183. logFile.write(
  184. str(nError) + ". There was a problem to persist the file " + detPage[key]['filename'] + " in the database.\n")
  185. persistError = True
  186. con.rollback()
  187. if not persistError:
  188. # move description files of completed folder
  189. source = line2.replace(os.path.basename(line2), "") + detPage[key]['filename']
  190. destination = line2.replace(os.path.basename(line2), "") + r'Read/'
  191. try:
  192. shutil.move(source, destination)
  193. num_persisted_moved += 1
  194. except:
  195. print("There was a problem to move the file " + detPage[key]['filename'] + " in the Description section!")
  196. nError += 1
  197. if createLog:
  198. logFile.write(
  199. str(nError) + ". There was a problem to move the file " + detPage[key]['filename'] + " in the Description section!.\n")
  200. moveError = True
  201. # if the associated description page is not read or not parsed
  202. else:
  203. # query database
  204. # if the product already exists:
  205. # num_in_db += 1
  206. pass
  207. # if number of products on listing page is equal to
  208. # the number of merged, persisted, and moved products plus
  209. # the number of products already in the database
  210. if not persistError and not moveError and len(rw) == (num_persisted_moved + num_in_db):
  211. # move listing file to completed folder
  212. source = line1
  213. destination = line1.replace(os.path.basename(line1), "") + r'Read/'
  214. try:
  215. shutil.move(source, destination)
  216. except:
  217. nError += 1
  218. print("There was a problem to move the file " + line1 + " in the Listing section!")
  219. if createLog:
  220. logFile.write(str(nError) + ". There was a problem to move the file " + line1 + " in the Listing section!.\n")
  221. # g.close ()
  222. if createLog:
  223. logFile.close()
  224. # end = time.time()
  225. # finalTime = float(end-ini)
  226. # print (marketPlace + " Parsing Perfomed Succesfully in %.2f" %finalTime + "!")
  227. input("Parsing the " + marketPlace + " marketplace and data classification done successfully. Press ENTER to continue\n")