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.

309 lines
10 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. '''
  3. Apocalypse Forum Crawler (Selenium)
  4. two captchas. if you get a captcha wrong you have to reload program.
  5. '''
  6. from selenium import webdriver
  7. from selenium.common.exceptions import NoSuchElementException
  8. from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
  9. from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
  10. from selenium.webdriver.firefox.service import Service
  11. from selenium.webdriver.support.ui import WebDriverWait
  12. from selenium.webdriver.support import expected_conditions as EC
  13. from selenium.webdriver.common.by import By
  14. from PIL import Image
  15. import urllib.parse as urlparse
  16. import os, re, time
  17. from datetime import date
  18. import subprocess
  19. import configparser
  20. from bs4 import BeautifulSoup
  21. from MarketPlaces.Initialization.prepare_parser import new_parse
  22. from MarketPlaces.Apocalypse.parser import apocalypse_links_parser
  23. from MarketPlaces.Utilities.utilities import cleanHTML
  24. counter = 1
  25. baseURL = 'http://apocam5hnoqskkmhr325nivjuh5phbmmggadxgcjabzzirap5iklkxad.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 = 'Apocalypse'
  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://apocam5hnoqskkmhr325nivjuh5phbmmggadxgcjabzzirap5iklkxad.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", 1)##
  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. 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. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  119. (By.XPATH, '//*[@id="name"]')))
  120. # entering username and password into input boxes
  121. usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="name"]')
  122. # Username here
  123. usernameBox.send_keys('shooby')
  124. passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="password"]')
  125. # Password here
  126. passwordBox.send_keys('perry_1the2_platypu$')
  127. input("Press ENTER when CAPTCHA is completed\n")
  128. # wait for listing page show up (This Xpath may need to change based on different seed url)
  129. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  130. (By.XPATH, "/html/body/div[1]/div[2]/div[1]/div[1]/a[13]")))
  131. # Saves the crawled html page, makes the directory path for html pages if not made
  132. def savePage(driver, page, url):
  133. cleanPage = cleanHTML(driver, page)
  134. filePath = getFullPathName(url)
  135. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  136. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  137. return
  138. # Gets the full path of the page to be saved along with its appropriate file name
  139. #@param: raw url as crawler crawls through every site
  140. def getFullPathName(url):
  141. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  142. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  143. fileName = getNameFromURL(url)
  144. if isDescriptionLink(url):
  145. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  146. else:
  147. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  148. return fullPath
  149. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  150. #@param: raw url as crawler crawls through every site
  151. def getNameFromURL(url):
  152. global counter
  153. name = ''.join(e for e in url if e.isalnum())
  154. if (name == ''):
  155. name = str(counter)
  156. counter = counter + 1
  157. return name
  158. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  159. #in this example, there are a couple of categories some threads fall under such as
  160. # Guides and Tutorials, Digital Products, and Software and Malware
  161. #as you can see they are categories of products
  162. def getInterestedLinks():
  163. links = []
  164. # # Hacking Services
  165. # links.append('http://apocam5hnoqskkmhr325nivjuh5phbmmggadxgcjabzzirap5iklkxad.onion/subcategory/19')
  166. # software and malware
  167. links.append('http://apocam5hnoqskkmhr325nivjuh5phbmmggadxgcjabzzirap5iklkxad.onion/subcategory/30')
  168. return links
  169. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  170. #topic and description pages are crawled through here, where both types of pages are saved
  171. #@param: selenium driver
  172. def crawlForum(driver):
  173. print("Crawling the Apocalypse market")
  174. linksToCrawl = getInterestedLinks()
  175. i = 0
  176. while i < len(linksToCrawl):
  177. link = linksToCrawl[i]
  178. print('Crawling :', link)
  179. try:
  180. has_next_page = True
  181. count = 0
  182. while has_next_page:
  183. try:
  184. driver.get(link)
  185. except:
  186. driver.refresh()
  187. html = driver.page_source
  188. savePage(driver, html, link)
  189. list = productPages(html)
  190. for item in list:
  191. itemURL = urlparse.urljoin(baseURL, str(item))
  192. try:
  193. driver.get(itemURL)
  194. except:
  195. driver.refresh()
  196. savePage(driver, driver.page_source, item)
  197. driver.back()
  198. # comment out
  199. # break
  200. # comment out
  201. if count == 1:
  202. break
  203. try:
  204. link = driver.find_element(by=By.XPATH, value=
  205. '/html/body/div[1]/div/div[2]/nav/ul/li[5]/a').get_attribute('href')
  206. if link == "":
  207. raise NoSuchElementException
  208. count += 1
  209. except NoSuchElementException:
  210. has_next_page = False
  211. except Exception as e:
  212. print(link, e)
  213. i += 1
  214. print("Crawling the Apocalypse market done.")
  215. # Returns 'True' if the link is a description link
  216. #@param: url of any url crawled
  217. #return: true if is a description page, false if not
  218. def isDescriptionLink(url):
  219. if 'article' in url:
  220. return True
  221. return False
  222. # Returns True if the link is a listingPage link
  223. #@param: url of any url crawled
  224. #return: true if is a Listing page, false if not
  225. def isListingLink(url):
  226. if 'subcategory' in url:
  227. return True
  228. return False
  229. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  230. #@param: link from interested link list ie. getInterestingLinks()
  231. #return: list of description links that should be crawled through
  232. def productPages(html):
  233. soup = BeautifulSoup(html, "html.parser")
  234. return apocalypse_links_parser(soup)
  235. # Drop links that "signout"
  236. # def isSignOut(url):
  237. # #absURL = urlparse.urljoin(url.base_url, url.url)
  238. # if 'signout' in url.lower() or 'logout' in url.lower():
  239. # return True
  240. #
  241. # return False
  242. def crawler():
  243. startCrawling()
  244. # print("Crawling and Parsing BestCardingWorld .... DONE!")