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.

333 lines
12 KiB

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