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.

332 lines
12 KiB

1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'DarkWeb'
  2. '''
  3. DarkFox Forum 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, time
  16. from datetime import date
  17. import subprocess
  18. from bs4 import BeautifulSoup
  19. from MarketPlaces.Initialization.prepare_parser import new_parse
  20. from MarketPlaces.DarkFox.parser import darkfox_links_parser
  21. from MarketPlaces.Utilities.utilities import cleanHTML
  22. counter = 1
  23. baseURL = 'http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/'
  24. # Opens Tor Browser, crawls the website, then parses, then closes tor
  25. #acts like the main method for the crawler, another function at the end of this code calls this function later
  26. def startCrawling():
  27. opentor()
  28. mktName = getMKTName()
  29. driver = getAccess()
  30. if driver != 'down':
  31. try:
  32. captcha(driver)
  33. crawlForum(driver)
  34. except Exception as e:
  35. print(driver.current_url, e)
  36. closetor(driver)
  37. new_parse(mktName, False)
  38. # Opens Tor Browser
  39. #prompts for ENTER input to continue
  40. def opentor():
  41. global pid
  42. print("Connecting Tor...")
  43. path = open('../../path.txt').readline().strip()
  44. pro = subprocess.Popen(path)
  45. pid = pro.pid
  46. time.sleep(7.5)
  47. input('Tor Connected. Press ENTER to continue\n')
  48. return
  49. # Returns the name of the website
  50. #return: name of site in string type
  51. def getMKTName():
  52. name = 'DarkFox'
  53. return name
  54. # Returns credentials needed for the mkt
  55. def getCredentials():
  56. credentials = 'blank blank blank blank cap 0'
  57. return credentials
  58. # Return the base link of the website
  59. #return: url of base site in string type
  60. def getFixedURL():
  61. url = 'http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/'
  62. return url
  63. # Closes Tor Browser
  64. #@param: current selenium driver
  65. def closetor(driver):
  66. # global pid
  67. # os.system("taskkill /pid " + str(pro.pid))
  68. # os.system("taskkill /t /f /im tor.exe")
  69. print('Closing Tor...')
  70. driver.close()
  71. time.sleep(3)
  72. return
  73. # Creates FireFox 'driver' and configure its 'Profile'
  74. # to use Tor proxy and socket
  75. def createFFDriver():
  76. file = open('../../path.txt', 'r')
  77. lines = file.readlines()
  78. ff_binary = FirefoxBinary(lines[0].strip())
  79. ff_prof = FirefoxProfile(lines[1].strip())
  80. # ff_prof.set_preference("places.history.enabled", False)
  81. # ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  82. # ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  83. # ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  84. # ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  85. # ff_prof.set_preference("signon.rememberSignons", False)
  86. # ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  87. # ff_prof.set_preference("network.dns.disablePrefetch", True)
  88. # ff_prof.set_preference("network.http.sendRefererHeader", 0)
  89. # ff_prof.set_preference("permissions.default.image", 2)
  90. # ff_prof.set_preference("browser.download.folderList", 2)
  91. # ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  92. # ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  93. ff_prof.set_preference('network.proxy.type', 1)
  94. ff_prof.set_preference("network.proxy.socks_version", 5)
  95. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  96. ff_prof.set_preference('network.proxy.socks_port', 9150)
  97. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  98. ff_prof.set_preference("javascript.enabled", False)
  99. ff_prof.update_preferences()
  100. service = Service(lines[2].strip())
  101. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  102. return driver
  103. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  104. #return: return the selenium driver or string 'down'
  105. def getAccess():
  106. url = getFixedURL()
  107. driver = createFFDriver()
  108. try:
  109. driver.get(url)
  110. return driver
  111. except:
  112. driver.close()
  113. return 'down'
  114. # Manual captcha solver, waits fora specific element so that the whole page loads, finds the input box, gets screenshot of captcha
  115. # then allows for manual solving of captcha in the terminal
  116. #@param: current selenium web driver
  117. def captcha(driver):
  118. # wait for captcha page show up
  119. WebDriverWait(driver, 100).until(EC.visibility_of_element_located((By.XPATH, "/html/body/div/div/form/button[1]")))
  120. # save captcha to local
  121. driver.find_element(by=By.XPATH, value="/html/body/div/div/form/div[1]/div[1]").screenshot(r'..\DarkFox\captcha.png')
  122. # open method used to open different extension image file
  123. im = Image.open(r'..\DarkFox\captcha.png')
  124. # This method will show image in any image viewer
  125. im.show()
  126. # wait until input space show up
  127. inputBox = driver.find_element(by=By.XPATH, value="/html/body/div/div/form/div[1]/div[2]/input")
  128. # ask user input captha solution in terminal
  129. userIn = input("Enter solution: ")
  130. # send user solution into the input space
  131. inputBox.send_keys(userIn)
  132. # click the verify(submit) button
  133. driver.find_element(by=By.XPATH, value="/html/body/div/div/form/button[1]").click()
  134. # wait for listing page show up (This Xpath may need to change based on different seed url)
  135. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  136. (By.XPATH, "/html/body/main/div/div/div[2]/div[1]/div[1]/form/div[1]/h1")))
  137. # Saves the crawled html page, makes the directory path for html pages if not made
  138. def savePage(page, url):
  139. cleanPage = cleanHTML(page)
  140. filePath = getFullPathName(url)
  141. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  142. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  143. return
  144. # Gets the full path of the page to be saved along with its appropriate file name
  145. #@param: raw url as crawler crawls through every site
  146. def getFullPathName(url):
  147. fileName = getNameFromURL(url)
  148. if isDescriptionLink(url):
  149. fullPath = r'..\DarkFox\HTML_Pages\\' + str(
  150. "%02d" % date.today().month) + str("%02d" % date.today().day) + str(
  151. "%04d" % date.today().year) + r'\\' + r'Description\\' + fileName + '.html'
  152. else:
  153. fullPath = r'..\DarkFox\HTML_Pages\\' + str(
  154. "%02d" % date.today().month) + str("%02d" % date.today().day) + str(
  155. "%04d" % date.today().year) + r'\\' + r'Listing\\' + fileName + '.html'
  156. return fullPath
  157. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  158. #@param: raw url as crawler crawls through every site
  159. def getNameFromURL(url):
  160. global counter
  161. name = ''.join(e for e in url if e.isalnum())
  162. if (name == ''):
  163. name = str(counter)
  164. counter = counter + 1
  165. return name
  166. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  167. #in this example, there are a couple of categories some threads fall under such as
  168. # Guides and Tutorials, Digital Products, and Software and Malware
  169. #as you can see they are categories of products
  170. def getInterestedLinks():
  171. links = []
  172. # # Guides and Tutorials
  173. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/30739153-1fcd-45cd-b919-072b439c6e06')
  174. # # Digital Products
  175. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/0e384d5f-26ef-4561-b5a3-ff76a88ab781')
  176. # Software and Malware
  177. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/6b71210f-f1f9-4aa3-8f89-bd9ee28f7afc')
  178. links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/6b71210f-f1f9-4aa3-8f89-bd9ee28f7afc?page=15')
  179. # # Services
  180. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/b9dc5846-5024-421e-92e6-09ba96a03280')
  181. # # Miscellaneous
  182. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/fd1c989b-1a74-4dc0-92b0-67d8c1c487cb')
  183. # # Hosting and Security
  184. # links.append('http://57d5j6bbwlpxbxe5tsjjy3vziktv3fo2o5j3nheo4gpg6lzpsimzqzid.onion/category/5233fd6a-72e6-466d-b108-5cc61091cd14')
  185. return links
  186. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  187. #topic and description pages are crawled through here, where both types of pages are saved
  188. #@param: selenium driver
  189. def crawlForum(driver):
  190. print("Crawling the DarkFox market")
  191. linksToCrawl = getInterestedLinks()
  192. # visited = set(linksToCrawl)
  193. # initialTime = time.time()
  194. count = 0
  195. i = 0
  196. while i < len(linksToCrawl):
  197. if count >= 500:
  198. break
  199. link = linksToCrawl[i]
  200. print('Crawling :', link)
  201. try:
  202. try:
  203. driver.get(link)
  204. except:
  205. driver.refresh()
  206. html = driver.page_source
  207. savePage(html, link)
  208. has_next_page = True
  209. while has_next_page:
  210. list = productPages(html)
  211. for item in list:
  212. itemURL = str(item)
  213. try:
  214. driver.get(itemURL)
  215. except:
  216. driver.refresh()
  217. savePage(driver.page_source, item)
  218. driver.back()
  219. count += 1
  220. try:
  221. link = driver.find_element(by=By.XPATH, value=
  222. '/html/body/main/div/div[2]/div/div[2]/div/div/div/nav/a[2]').get_attribute('href')
  223. try:
  224. driver.get(link)
  225. except:
  226. driver.refresh()
  227. html = driver.page_source
  228. savePage(html, link)
  229. except NoSuchElementException:
  230. has_next_page = False
  231. except Exception as e:
  232. print(link, e)
  233. i += 1
  234. # finalTime = time.time()
  235. # print finalTime - initialTime
  236. input("Crawling BestCardingWorld forum done sucessfully. Press ENTER to continue\n")
  237. # Returns 'True' if the link is a description link
  238. #@param: url of any url crawled
  239. #return: true if is a description page, false if not
  240. def isDescriptionLink(url):
  241. if 'product' in url:
  242. return True
  243. return False
  244. # Returns True if the link is a listingPage link
  245. #@param: url of any url crawled
  246. #return: true if is a Listing page, false if not
  247. def isListingLink(url):
  248. if 'category' in url:
  249. return True
  250. return False
  251. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  252. #@param: link from interested link list ie. getInterestingLinks()
  253. #return: list of description links that should be crawled through
  254. def productPages(html):
  255. soup = BeautifulSoup(html, "html.parser")
  256. return darkfox_links_parser(soup)
  257. # Drop links that "signout"
  258. def isSignOut(url):
  259. #absURL = urlparse.urljoin(url.base_url, url.url)
  260. if 'signout' in url.lower() or 'logout' in url.lower():
  261. return True
  262. return False
  263. def crawler():
  264. startCrawling()
  265. # print("Crawling and Parsing BestCardingWorld .... DONE!")