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.

336 lines
12 KiB

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