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.

283 lines
9.9 KiB

1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. '''
  3. M00nkeyMarket Forum Crawler (Selenium) incomplete
  4. might be impossible to crawl
  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. BASE_URL = 'http://moonkey4f2mkcp6hpackeea356puiry27h3dz3hzbt3adbmsk4gs7wyd.onion/'
  26. MARKET_NAME = 'M00nkeyMarket'
  27. # Opens Tor Browser, crawls the website, then parses, then closes tor
  28. #acts like the main method for the crawler, another function at the end of this code calls this function later
  29. def startCrawling():
  30. driver = getAccess()
  31. if driver != 'down':
  32. try:
  33. login(driver)
  34. crawlForum(driver)
  35. except Exception as e:
  36. print(driver.current_url, e)
  37. closeDriver(driver)
  38. new_parse(MARKET_NAME, BASE_URL, True)
  39. # Returns the name of the website
  40. #return: name of site in string type
  41. # def getMKTName():
  42. # name = 'M00nkeyMarket'
  43. # return name
  44. # Return the base link of the website
  45. #return: url of base site in string type
  46. # def getFixedURL():
  47. # url = 'http://moonkey4f2mkcp6hpackeea356puiry27h3dz3hzbt3adbmsk4gs7wyd.onion/'
  48. # return url
  49. # Closes Tor Browser
  50. #@param: current selenium driver
  51. def closeDriver(driver):
  52. # global pid
  53. # os.system("taskkill /pid " + str(pro.pid))
  54. # os.system("taskkill /t /f /im tor.exe")
  55. print('Closing Tor...')
  56. driver.close()
  57. time.sleep(3)
  58. return
  59. # Creates FireFox 'driver' and configure its 'Profile'
  60. # to use Tor proxy and socket
  61. def createFFDriver():
  62. from MarketPlaces.Initialization.markets_mining import config
  63. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  64. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  65. ff_prof.set_preference("places.history.enabled", False)
  66. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  67. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  68. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  69. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  70. ff_prof.set_preference("signon.rememberSignons", False)
  71. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  72. ff_prof.set_preference("network.dns.disablePrefetch", True)
  73. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  74. ff_prof.set_preference("permissions.default.image", 3)
  75. ff_prof.set_preference("browser.download.folderList", 2)
  76. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  77. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  78. ff_prof.set_preference('network.proxy.type', 1)
  79. ff_prof.set_preference("network.proxy.socks_version", 5)
  80. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  81. ff_prof.set_preference('network.proxy.socks_port', 9150)
  82. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  83. ff_prof.set_preference("javascript.enabled", False)
  84. ff_prof.update_preferences()
  85. service = Service(config.get('TOR', 'geckodriver_path'))
  86. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  87. driver.maximize_window()
  88. return driver
  89. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  90. #return: return the selenium driver or string 'down'
  91. def getAccess():
  92. driver = createFFDriver()
  93. try:
  94. driver.get(BASE_URL)
  95. return driver
  96. except:
  97. driver.close()
  98. return 'down'
  99. # Manual captcha solver, waits fora specific element so that the whole page loads, finds the input box, gets screenshot of captcha
  100. # then allows for manual solving of captcha in the terminal
  101. #@param: current selenium web driver
  102. def login(driver):
  103. input("Press ENTER when CAPTCHA is completed. This will fill in your login credentials\n")
  104. # wait for page to show up (This Xpath may need to change based on different seed url)
  105. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  106. (By.XPATH, '//*[@id="username"]')))
  107. # entering username and password into input boxes
  108. usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="username"]')
  109. # Username here
  110. usernameBox.send_keys('riprobinwilliams')
  111. passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="password"]')
  112. # Password here
  113. passwordBox.send_keys('genie_show_metheWorld')
  114. input("Press ENTER when CAPTCHA and exit pressed is completed\nWAIT FOR PAGE TO LOAD SOMETIMES THY SEND NEWSLETTERS")
  115. # wait for listing page show up (This Xpath may need to change based on different seed url)
  116. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  117. (By.XPATH, "/html/body/div/div[2]/div/div/div/div/div/div[1]/a/img")))
  118. # Saves the crawled html page, makes the directory path for html pages if not made
  119. def savePage(driver, page, url):
  120. cleanPage = cleanHTML(driver, page)
  121. filePath = getFullPathName(url)
  122. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  123. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  124. return
  125. # Gets the full path of the page to be saved along with its appropriate file name
  126. #@param: raw url as crawler crawls through every site
  127. def getFullPathName(url):
  128. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  129. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + MARKET_NAME + "/HTML_Pages")
  130. fileName = getNameFromURL(url)
  131. if isDescriptionLink(url):
  132. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  133. else:
  134. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  135. return fullPath
  136. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  137. #@param: raw url as crawler crawls through every site
  138. def getNameFromURL(url):
  139. global counter
  140. name = ''.join(e for e in url if e.isalnum())
  141. if (name == ''):
  142. name = str(counter)
  143. counter = counter + 1
  144. return name
  145. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  146. #in this example, there are a couple of categories some threads fall under such as
  147. # Guides and Tutorials, Digital Products, and Software and Malware
  148. #as you can see they are categories of products
  149. def getInterestedLinks():
  150. links = []
  151. # software
  152. links.append('http://moonkey4f2mkcp6hpackeea356puiry27h3dz3hzbt3adbmsk4gs7wyd.onion/search/subcategories?subcategory=30')
  153. # # guides
  154. # links.append('http://moonkey4f2mkcp6hpackeea356puiry27h3dz3hzbt3adbmsk4gs7wyd.onion/search/subcategories?subcategory=17')
  155. return links
  156. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  157. #topic and description pages are crawled through here, where both types of pages are saved
  158. #@param: selenium driver
  159. def crawlForum(driver):
  160. print("Crawling the M00nkeyMarket market")
  161. linksToCrawl = getInterestedLinks()
  162. i = 0
  163. while i < len(linksToCrawl):
  164. link = linksToCrawl[i]
  165. print('Crawling :', link)
  166. try:
  167. has_next_page = True
  168. count = 0
  169. while has_next_page:
  170. try:
  171. driver.get(link)
  172. except:
  173. driver.refresh()
  174. html = driver.page_source
  175. savePage(driver, html, link)
  176. list = productPages(html)
  177. for item in list:
  178. itemURL = urlparse.urljoin(BASE_URL, str(item))
  179. try:
  180. driver.get(itemURL)
  181. except:
  182. driver.refresh()
  183. savePage(driver, driver.page_source, item)
  184. driver.back()
  185. # comment out
  186. break
  187. # comment out
  188. if count == 1:
  189. break
  190. try:
  191. link = driver.find_element(by=By.LINK_TEXT, value='Next ›').get_attribute('href')
  192. if link == "":
  193. raise NoSuchElementException
  194. count += 1
  195. except NoSuchElementException:
  196. has_next_page = False
  197. except Exception as e:
  198. print(link, e)
  199. i += 1
  200. print("Crawling the M00nkeyMarket done.")
  201. # Returns 'True' if the link is a description link
  202. #@param: url of any url crawled
  203. #return: true if is a description page, false if not
  204. def isDescriptionLink(url):
  205. if 'listings' in url:
  206. return True
  207. return False
  208. # Returns True if the link is a listingPage link
  209. #@param: url of any url crawled
  210. #return: true if is a Listing page, false if not
  211. def isListingLink(url):
  212. if 'subcategory' in url:
  213. return True
  214. return False
  215. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  216. #@param: link from interested link list ie. getInterestingLinks()
  217. #return: list of description links that should be crawled through
  218. def productPages(html):
  219. soup = BeautifulSoup(html, "html.parser")
  220. return m00nkey_links_parser(soup)
  221. def crawler():
  222. startCrawling()
  223. # print("Crawling and Parsing BestCardingWorld .... DONE!")