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
11 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. '''
  3. M00nkeyMarket Forum Crawler (Selenium) incomplete
  4. having trouble checking it due to the captcha
  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.M00nkeyMarket.parser import m00nkey_links_parser
  23. from MarketPlaces.Utilities.utilities import cleanHTML
  24. counter = 1
  25. baseURL = 'http://moonkey4f2mkcp6hpackeea356puiry27h3dz3hzbt3adbmsk4gs7wyd.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(forumName, baseURL, False)
  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 = 'M00nkeyMarket'
  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://moonkey4f2mkcp6hpackeea356puiry27h3dz3hzbt3adbmsk4gs7wyd.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. return driver
  100. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  101. #return: return the selenium driver or string 'down'
  102. def getAccess():
  103. url = getFixedURL()
  104. driver = createFFDriver()
  105. try:
  106. driver.get(url)
  107. return driver
  108. except:
  109. driver.close()
  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 login(driver):
  115. input("Press ENTER when CAPTCHA is completed\n")
  116. # wait for 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, '//*[@id="username"]')))
  119. # entering username and password into input boxes
  120. usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="username"]')
  121. # Username here
  122. usernameBox.send_keys('riprobinwilliams')
  123. passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="password"]')
  124. # Password here
  125. passwordBox.send_keys('genie_show_metheWorld')
  126. input("Press ENTER when CAPTCHA and anti-phishing is completed\n")
  127. # wait for listing page show up (This Xpath may need to change based on different seed url)
  128. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  129. (By.XPATH, "/html/body/div/div[1]/div/div/div[2]/div[3]/div/ul/li[2]/ul/li[5]/a")))
  130. # Saves the crawled html page, makes the directory path for html pages if not made
  131. def savePage(page, url):
  132. cleanPage = cleanHTML(page)
  133. filePath = getFullPathName(url)
  134. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  135. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  136. return
  137. # Gets the full path of the page to be saved along with its appropriate file name
  138. #@param: raw url as crawler crawls through every site
  139. def getFullPathName(url):
  140. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  141. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  142. fileName = getNameFromURL(url)
  143. if isDescriptionLink(url):
  144. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  145. else:
  146. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  147. return fullPath
  148. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  149. #@param: raw url as crawler crawls through every site
  150. def getNameFromURL(url):
  151. global counter
  152. name = ''.join(e for e in url if e.isalnum())
  153. if (name == ''):
  154. name = str(counter)
  155. counter = counter + 1
  156. return name
  157. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  158. #in this example, there are a couple of categories some threads fall under such as
  159. # Guides and Tutorials, Digital Products, and Software and Malware
  160. #as you can see they are categories of products
  161. def getInterestedLinks():
  162. links = []
  163. # software
  164. links.append('http://moonkey4f2mkcp6hpackeea356puiry27h3dz3hzbt3adbmsk4gs7wyd.onion/search/subcategories?subcategory=30')
  165. # # guides
  166. # links.append('http://moonkey4f2mkcp6hpackeea356puiry27h3dz3hzbt3adbmsk4gs7wyd.onion/search/subcategories?subcategory=17')
  167. return links
  168. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  169. #topic and description pages are crawled through here, where both types of pages are saved
  170. #@param: selenium driver
  171. def crawlForum(driver):
  172. print("Crawling the M00nkeyMarket market")
  173. linksToCrawl = getInterestedLinks()
  174. visited = set(linksToCrawl)
  175. initialTime = time.time()
  176. count = 0
  177. i = 0
  178. while i < len(linksToCrawl):
  179. link = linksToCrawl[i]
  180. print('Crawling :', link)
  181. try:
  182. try:
  183. driver.get(link)
  184. except:
  185. driver.refresh()
  186. html = driver.page_source
  187. savePage(html, link)
  188. has_next_page = True
  189. while has_next_page:
  190. list = productPages(html)
  191. for item in list:
  192. itemURL = urlparse.urljoin(baseURL, str(item))
  193. try:
  194. driver.get(itemURL)
  195. except:
  196. driver.refresh()
  197. savePage(driver.page_source, item)
  198. driver.back()
  199. # comment out
  200. break
  201. # comment out
  202. if count == 1:
  203. count = 0
  204. break
  205. try:
  206. temp = driver.find_element(by=By.XPATH, value='/html/body/div/div[1]/div/div/div[3]/div/div[3]/nav')
  207. link = temp.find_element(by=By.CLASS_NAME, value='next ml-1 mt-1').get_attribute('href')
  208. if link == "":
  209. raise NoSuchElementException
  210. try:
  211. driver.get(link)
  212. except:
  213. driver.refresh()
  214. html = driver.page_source
  215. savePage(html, link)
  216. count += 1
  217. except NoSuchElementException:
  218. has_next_page = False
  219. except Exception as e:
  220. print(link, e)
  221. i += 1
  222. # finalTime = time.time()
  223. # print finalTime - initialTime
  224. input("Crawling M00nkeyMarket done sucessfully. Press ENTER to continue\n")
  225. # Returns 'True' if the link is a description link
  226. #@param: url of any url crawled
  227. #return: true if is a description page, false if not
  228. def isDescriptionLink(url):
  229. if 'listings' in url:
  230. return True
  231. return False
  232. # Returns True if the link is a listingPage link
  233. #@param: url of any url crawled
  234. #return: true if is a Listing page, false if not
  235. def isListingLink(url):
  236. if 'subcategory' in url:
  237. return True
  238. return False
  239. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  240. #@param: link from interested link list ie. getInterestingLinks()
  241. #return: list of description links that should be crawled through
  242. def productPages(html):
  243. soup = BeautifulSoup(html, "html.parser")
  244. return m00nkey_links_parser(soup)
  245. def crawler():
  246. startCrawling()
  247. # print("Crawling and Parsing BestCardingWorld .... DONE!")