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.

297 lines
10 KiB

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