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.

289 lines
10 KiB

  1. __author__ = 'Helium'
  2. '''
  3. Nexus Market Crawler (Selenium)
  4. '''
  5. from selenium import webdriver
  6. from selenium.common.exceptions import NoSuchElementException
  7. from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
  8. from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
  9. from selenium.webdriver.firefox.service import Service
  10. from selenium.webdriver.support.ui import WebDriverWait
  11. from selenium.webdriver.support import expected_conditions as EC
  12. from selenium.webdriver.common.by import By
  13. from PIL import Image
  14. import urllib.parse as urlparse
  15. import os, re, time
  16. from datetime import date
  17. import subprocess
  18. import configparser
  19. from bs4 import BeautifulSoup
  20. from MarketPlaces.Initialization.prepare_parser import new_parse
  21. from MarketPlaces.Nexus.parser import nexus_links_parser
  22. from MarketPlaces.Utilities.utilities import cleanHTML
  23. counter = 1
  24. baseURL = 'http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion'
  25. # Opens Tor Browser, crawls the website, then parses, then closes tor
  26. #acts like the main method for the crawler, another function at the end of this code calls this function later
  27. def startCrawling():
  28. mktName = getMKTName()
  29. driver = getAccess()
  30. if driver != 'down':
  31. try:
  32. input("Press ENTER when page loads after DDOS protection")
  33. crawlForum(driver)
  34. except Exception as e:
  35. print(driver.current_url, e)
  36. closeDriver(driver)
  37. new_parse(mktName, baseURL, True)
  38. # Returns the name of the website
  39. #return: name of site in string type
  40. def getMKTName():
  41. name = 'Nexus'
  42. return name
  43. # Return the base link of the website
  44. #return: url of base site in string type
  45. def getFixedURL():
  46. url = 'http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion'
  47. return url
  48. # Closes Tor Browser
  49. #@param: current selenium driver
  50. def closeDriver(driver):
  51. # global pid
  52. # os.system("taskkill /pid " + str(pro.pid))
  53. # os.system("taskkill /t /f /im tor.exe")
  54. print('Closing Tor...')
  55. driver.close()
  56. time.sleep(3)
  57. return
  58. # Creates FireFox 'driver' and configure its 'Profile'
  59. # to use Tor proxy and socket
  60. def createFFDriver():
  61. from MarketPlaces.Initialization.markets_mining import config
  62. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  63. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  64. ff_prof.set_preference("places.history.enabled", False)
  65. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  66. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  67. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  68. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  69. ff_prof.set_preference("signon.rememberSignons", False)
  70. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  71. # ff_prof.set_preference("network.dns.disablePrefetch", True)
  72. # ff_prof.set_preference("network.http.sendRefererHeader", 0)
  73. ff_prof.set_preference("permissions.default.image", 3)
  74. ff_prof.set_preference("browser.download.folderList", 2)
  75. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  76. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  77. ff_prof.set_preference('network.proxy.type', 1)
  78. ff_prof.set_preference("network.proxy.socks_version", 5)
  79. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  80. ff_prof.set_preference('network.proxy.socks_port', 9150)
  81. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  82. ff_prof.set_preference("javascript.enabled", True)
  83. ff_prof.update_preferences()
  84. service = Service(config.get('TOR', 'geckodriver_path'))
  85. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  86. driver.maximize_window()
  87. return driver
  88. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  89. #return: return the selenium driver or string 'down'
  90. def getAccess():
  91. url = getFixedURL()
  92. driver = createFFDriver()
  93. try:
  94. driver.get(url)
  95. return driver
  96. except:
  97. driver.close()
  98. return 'down'
  99. def savePage(driver, page, url):
  100. cleanPage = cleanHTML(driver, page)
  101. filePath = getFullPathName(url)
  102. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  103. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  104. return
  105. # Gets the full path of the page to be saved along with its appropriate file name
  106. #@param: raw url as crawler crawls through every site
  107. def getFullPathName(url):
  108. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  109. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  110. fileName = getNameFromURL(url)
  111. if isListingLink(url):
  112. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  113. else:
  114. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  115. return fullPath
  116. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  117. #@param: raw url as crawler crawls through every site
  118. def getNameFromURL(url):
  119. global counter
  120. name = ''.join(e for e in url if e.isalnum())
  121. if (name == ''):
  122. name = str(counter)
  123. counter = counter + 1
  124. return name
  125. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  126. #in this example, there are a couple of categories some threads fall under such as
  127. # Guides and Tutorials, Digital Products, and Software and Malware
  128. #as you can see they are categories of products
  129. def getInterestedLinks():
  130. links = []
  131. # malware
  132. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/malware/')
  133. # hacking-spam
  134. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/hacking-spam/')
  135. # hacking services
  136. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/servicos/hacking/')
  137. # programming services
  138. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/servicos/programacao/')
  139. # remote admin services
  140. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/servicos/administracao-remota/')
  141. # hacking guides
  142. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/guias-tutoriais/guia-de-hacking/')
  143. # malware guides
  144. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/guias-tutoriais/guia-de-malware/')
  145. # fraud guides
  146. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/guias-tutoriais/guia-de-fraudes/')
  147. # fraud software
  148. links.append('http://nexus2bmba34euohk3xo7og2zelkgbtc2p7rjsbxrjjknlecja2tdvyd.onion/categoria-produto/fraudes/software-de-fraude/')
  149. return links
  150. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  151. #topic and description pages are crawled through here, where both types of pages are saved
  152. #@param: selenium driver
  153. def crawlForum(driver):
  154. print("Crawling the Nexus market")
  155. linksToCrawl = getInterestedLinks()
  156. i = 0
  157. while i < len(linksToCrawl):
  158. link = linksToCrawl[i]
  159. print('Crawling :', link)
  160. try:
  161. has_next_page = True
  162. count = 0
  163. while has_next_page:
  164. try:
  165. driver.get(link)
  166. except:
  167. driver.refresh()
  168. # waiting for btc price to load
  169. try:
  170. WebDriverWait(driver, 1).until(EC.visibility_of_element_located(
  171. (By.XPATH, "/html/body/div[1]/div[2]/div/div/main/ul/li[1]/div/span/span[3]")))
  172. time.sleep(5)
  173. except:
  174. pass
  175. html = driver.page_source
  176. savePage(driver, html, link)
  177. list = productPages(html)
  178. for item in list:
  179. itemURL = urlparse.urljoin(baseURL, str(item))
  180. try:
  181. driver.get(itemURL)
  182. except:
  183. driver.refresh()
  184. # waiting for btc price to load
  185. try:
  186. WebDriverWait(driver, 1).until(EC.visibility_of_element_located(
  187. (By.XPATH, "/html/body/div[1]/div[2]/div/div/main/div[3]/div[2]/p/span[3]")))
  188. except:
  189. pass
  190. savePage(driver, driver.page_source, item)
  191. driver.back()
  192. # # comment out
  193. # break
  194. #
  195. # # comment out
  196. # if count == 1:
  197. # break
  198. try:
  199. link = driver.find_element(by=By.LINK_TEXT, value='').get_attribute('href')
  200. if link == "":
  201. raise NoSuchElementException
  202. count += 1
  203. except NoSuchElementException:
  204. has_next_page = False
  205. except Exception as e:
  206. print(link, e)
  207. i += 1
  208. print("Crawling the Nexus market done.")
  209. # Returns 'True' if the link is a description link
  210. #@param: url of any url crawled
  211. #return: true if is a description page, false if not
  212. def isDescriptionLink(url):
  213. if 'produto' in url:
  214. return True
  215. return False
  216. # Returns True if the link is a listingPage link
  217. #@param: url of any url crawled
  218. #return: true if is a Listing page, false if not
  219. def isListingLink(url):
  220. if 'categoria-produto' in url:
  221. return True
  222. return False
  223. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  224. #@param: link from interested link list ie. getInterestingLinks()
  225. #return: list of description links that should be crawled through
  226. def productPages(html):
  227. soup = BeautifulSoup(html, "html.parser")
  228. return nexus_links_parser(soup)
  229. def crawler():
  230. startCrawling()
  231. # print("Crawling and Parsing Nexus .... DONE!")