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.

325 lines
12 KiB

  1. __author__ = 'DarkWeb'
  2. '''
  3. ViceCity Market 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. import configparser
  19. import subprocess
  20. from bs4 import BeautifulSoup
  21. from MarketPlaces.Initialization.prepare_parser import new_parse
  22. from MarketPlaces.ViceCity.parser import vicecity_links_parser
  23. from MarketPlaces.Utilities.utilities import cleanHTML
  24. counter = 1
  25. baseURL = 'http://52qlucglu6fuaqist2herssakipapig2higaaayu7446n55xw4ylxqid.onion/'
  26. # Opens Tor Browser, crawls the website, then parses, then closes tor
  27. #acts like the main method for the crawler, another function at the end of this code calls this function later
  28. def startCrawling():
  29. # opentor()
  30. mktName = getMKTName()
  31. driver = getAccess()
  32. if driver != 'down':
  33. try:
  34. login(driver)
  35. crawlForum(driver)
  36. except Exception as e:
  37. print(driver.current_url, e)
  38. closetor(driver)
  39. new_parse(mktName, baseURL, True)
  40. # Opens Tor Browser
  41. #prompts for ENTER input to continue
  42. def opentor():
  43. from MarketPlaces.Initialization.markets_mining import config
  44. global pid
  45. print("Connecting Tor...")
  46. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  47. pid = pro.pid
  48. time.sleep(7.5)
  49. input('Tor Connected. Press ENTER to continue\n')
  50. return
  51. # Returns the name of the website
  52. #return: name of site in string type
  53. def getMKTName():
  54. name = 'ViceCity'
  55. return name
  56. # Return the base link of the website
  57. #return: url of base site in string type
  58. def getFixedURL():
  59. url = 'http://52qlucglu6fuaqist2herssakipapig2higaaayu7446n55xw4ylxqid.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. from MarketPlaces.Initialization.markets_mining import config
  75. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  76. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  77. # ff_prof.set_preference("places.history.enabled", False)
  78. # ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  79. # ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  80. # ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  81. # ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  82. # ff_prof.set_preference("signon.rememberSignons", False)
  83. # ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  84. # ff_prof.set_preference("network.dns.disablePrefetch", True)
  85. # ff_prof.set_preference("network.http.sendRefererHeader", 0)
  86. # ff_prof.set_preference("permissions.default.image", 3)
  87. # ff_prof.set_preference("browser.download.folderList", 2)
  88. # ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  89. # ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  90. ff_prof.set_preference('network.proxy.type', 1)
  91. ff_prof.set_preference("network.proxy.socks_version", 5)
  92. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  93. ff_prof.set_preference('network.proxy.socks_port', 9150)
  94. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  95. ff_prof.set_preference("javascript.enabled", False)
  96. ff_prof.update_preferences()
  97. service = Service(config.get('TOR', 'geckodriver_path'))
  98. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  99. driver.maximize_window()
  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. # wait for first captcha page to show up (This Xpath may need to change based on different seed url)
  117. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  118. (By.XPATH, "/html/body/div/div/form/div/div[1]")))
  119. input("Press Enter once captcha done")
  120. #clicks button after captcha is inputted
  121. # driver.find_element(by=By.XPATH, value='/html/body/div/div/form/button').click()
  122. #wait for login page to show up
  123. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  124. (By.XPATH, '/html/body/div/div/div/form')))
  125. #puts username into box
  126. userBox = driver.find_element(by=By.XPATH, value='//*[@id="username"]')
  127. userBox.send_keys('ct1234')
  128. #waits for second catpcha to be inputted by user
  129. input("Press Enter once captcha done")
  130. #clicks on continue
  131. # driver.find_element(by=By.XPATH, value='/html/body/div/div/div/form/input[2]').click()
  132. #waits for password to show
  133. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  134. (By.XPATH, '/html/body/div/div/div/form/div[3]/input')))
  135. time.sleep(10) # give time for site to catch up
  136. # puts password into box
  137. passBox = driver.find_element(by=By.XPATH, value='/html/body/div/div/div/form/div[2]/input')
  138. passBox.send_keys('DementedBed123-')
  139. driver.find_element(by=By.XPATH, value='/html/body/div/div/div/form/div[3]/input').click()
  140. # wait for pin input to show
  141. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  142. (By.XPATH, '/html/body/div[1]/div/form/span')))
  143. pinBox = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div/form/input[1]')
  144. pinBox.send_keys('12345')
  145. driver.find_element(by=By.XPATH, value='/html/body/div[1]/div/form/input[2]').click()
  146. # waits for main listing page before crawling to ensure everything goes well
  147. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  148. (By.XPATH, '/html/body/div[1]/div/div[2]')))
  149. # Saves the crawled html page, makes the directory path for html pages if not made
  150. def savePage(driver, page, url):
  151. cleanPage = cleanHTML(driver, page)
  152. filePath = getFullPathName(url)
  153. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  154. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  155. return
  156. # Gets the full path of the page to be saved along with its appropriate file name
  157. #@param: raw url as crawler crawls through every site
  158. def getFullPathName(url):
  159. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  160. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  161. fileName = getNameFromURL(url)
  162. if isDescriptionLink(url):
  163. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  164. else:
  165. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  166. return fullPath
  167. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  168. #@param: raw url as crawler crawls through every site
  169. def getNameFromURL(url):
  170. global counter
  171. name = ''.join(e for e in url if e.isalnum())
  172. if (name == ''):
  173. name = str(counter)
  174. counter = counter + 1
  175. return name
  176. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  177. #in this example, there are a couple of categories some threads fall under such as
  178. # Guides and Tutorials, Digital Products, and Software and Malware
  179. #as you can see they are categories of products
  180. def getInterestedLinks():
  181. links = []
  182. # Digital - Fraud Software, Has Hacking and Guides
  183. links.append('http://52qlucglu6fuaqist2herssakipapig2higaaayu7446n55xw4ylxqid.onion/?category=150')
  184. # # Digital - Guides and Tutorials
  185. # links.append('http://52qlucglu6fuaqist2herssakipapig2higaaayu7446n55xw4ylxqid.onion/?category=94')
  186. # # Carding Services
  187. # links.append('http://52qlucglu6fuaqist2herssakipapig2higaaayu7446n55xw4ylxqid.onion/?category=155')
  188. # # Digital - Other (half junk half random stuff like: bots, rats, viruses, and guides)
  189. # links.append('http://52qlucglu6fuaqist2herssakipapig2higaaayu7446n55xw4ylxqid.onion/?category=153')
  190. return links
  191. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  192. #topic and description pages are crawled through here, where both types of pages are saved
  193. #@param: selenium driver
  194. def crawlForum(driver):
  195. print("Crawling the ViceCity Market")
  196. linksToCrawl = getInterestedLinks()
  197. i = 0
  198. while i < len(linksToCrawl):
  199. link = linksToCrawl[i]
  200. print('Crawling :', link)
  201. try:
  202. has_next_page = True
  203. count = 0
  204. while has_next_page:
  205. try:
  206. driver.get(link)
  207. except:
  208. driver.refresh()
  209. html = driver.page_source
  210. savePage(driver, html, link)
  211. list = productPages(html)
  212. for item in list:
  213. itemURL = urlparse.urljoin(baseURL, str(item))
  214. try:
  215. driver.get(itemURL)
  216. except:
  217. driver.refresh()
  218. time.sleep(2.5) # to let page catchup
  219. savePage(driver, driver.page_source, item)
  220. time.sleep(2.5) # so site doesnt crash
  221. driver.back()
  222. # comment out
  223. # break
  224. # comment out
  225. if count == 1:
  226. break
  227. try:
  228. temp = driver.find_element(by=By.CLASS_NAME, value='pagination')
  229. link = temp.find_element(by=By.LINK_TEXT, value='Next').get_attribute('href')
  230. if link == "":
  231. raise NoSuchElementException
  232. count += 1
  233. except NoSuchElementException:
  234. has_next_page = False
  235. except Exception as e:
  236. print(link, e)
  237. i += 1
  238. print("Crawling the ViceCity market done.")
  239. # Returns 'True' if the link is a description link
  240. #@param: url of any url crawled
  241. #return: true if is a description page, false if not
  242. def isDescriptionLink(url):
  243. if 'listing' in url:
  244. return True
  245. return False
  246. # Returns True if the link is a listingPage link
  247. #@param: url of any url crawled
  248. #return: true if is a Listing page, false if not
  249. def isListingLink(url):
  250. if 'category' in url:
  251. return True
  252. return False
  253. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  254. #@param: link from interested link list ie. getInterestingLinks()
  255. #return: list of description links that should be crawled through
  256. def productPages(html):
  257. soup = BeautifulSoup(html, "html.parser")
  258. return vicecity_links_parser(soup)
  259. def crawler():
  260. startCrawling()
  261. # print("Crawling and Parsing BestCardingWorld .... DONE!")