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.

291 lines
10 KiB

  1. __author__ = 'Helium'
  2. '''
  3. MetaVerseMarket Marketplace 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, re, time
  16. from datetime import date
  17. import subprocess
  18. import configparser
  19. from bs4 import BeautifulSoup
  20. from MarketPlaces.Initialization.prepare_parser import new_parse
  21. from MarketPlaces.MetaVerseMarket.parser import metaversemarket_links_parser
  22. from MarketPlaces.Utilities.utilities import cleanHTML
  23. counter = 1
  24. baseURL = 'http://mdbvvcfwl3fpckiraucv7gio57yoslnhfjxzpoihf4fgdkdd7bwyv7id.onion/login'
  25. # Opens Tor Browser, crawls the website, then parses, then closes tor
  26. #acts like the main method for the crawler, another function at the end of this code calls this function later
  27. def startCrawling():
  28. mktName = getMKTName()
  29. driver = getAccess()
  30. if driver != 'down':
  31. try:
  32. login(driver)
  33. crawlForum(driver)
  34. except Exception as e:
  35. print(driver.current_url, e)
  36. closeDriver(driver)
  37. new_parse(mktName, baseURL, True)
  38. # Returns the name of the website
  39. #return: name of site in string type
  40. def getMKTName():
  41. name = 'MetaVerseMarket'
  42. return name
  43. # Return the base link of the website
  44. #return: url of base site in string type
  45. def getFixedURL():
  46. url = 'http://mdbvvcfwl3fpckiraucv7gio57yoslnhfjxzpoihf4fgdkdd7bwyv7id.onion/login'
  47. return url
  48. # Closes Tor Browser
  49. #@param: current selenium driver
  50. def closeDriver(driver):
  51. # global pid
  52. # os.system("taskkill /pid " + str(pro.pid))
  53. # os.system("taskkill /t /f /im tor.exe")
  54. print('Closing Tor...')
  55. driver.close()
  56. time.sleep(3)
  57. return
  58. # Creates FireFox 'driver' and configure its 'Profile'
  59. # to use Tor proxy and socket
  60. def createFFDriver():
  61. from MarketPlaces.Initialization.markets_mining import config
  62. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  63. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  64. ff_prof.set_preference("places.history.enabled", False)
  65. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  66. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  67. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  68. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  69. ff_prof.set_preference("signon.rememberSignons", False)
  70. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  71. ff_prof.set_preference("network.dns.disablePrefetch", True)
  72. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  73. ff_prof.set_preference("permissions.default.image", 3)
  74. ff_prof.set_preference("browser.download.folderList", 2)
  75. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  76. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  77. ff_prof.set_preference('network.proxy.type', 1)
  78. ff_prof.set_preference("network.proxy.socks_version", 5)
  79. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  80. ff_prof.set_preference('network.proxy.socks_port', 9150)
  81. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  82. ff_prof.set_preference("javascript.enabled", False)
  83. ff_prof.update_preferences()
  84. service = Service(config.get('TOR', 'geckodriver_path'))
  85. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  86. driver.maximize_window()
  87. return driver
  88. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  89. #return: return the selenium driver or string 'down'
  90. def getAccess():
  91. url = getFixedURL()
  92. driver = createFFDriver()
  93. try:
  94. driver.get(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. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  104. (By.XPATH, '//*[@id="username"]')))
  105. # entering username and password into input boxes
  106. usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="username"]')
  107. # Username here
  108. usernameBox.send_keys('metotomoto')
  109. passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="password"]')
  110. # Password here
  111. passwordBox.send_keys('lionking_kumba1ya')
  112. input("Press ENTER when CAPTCHA is completed and you exit the newsletter\n")
  113. # wait for listing page show up (This Xpath may need to change based on different seed url)
  114. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  115. (By.XPATH, '//*[@id="searchq"]')))
  116. # Saves the crawled html page, makes the directory path for html pages if not made
  117. def savePage(driver, page, url):
  118. cleanPage = cleanHTML(driver, page)
  119. filePath = getFullPathName(url)
  120. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  121. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  122. return
  123. # Gets the full path of the page to be saved along with its appropriate file name
  124. #@param: raw url as crawler crawls through every site
  125. def getFullPathName(url):
  126. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  127. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  128. fileName = getNameFromURL(url)
  129. if isDescriptionLink(url):
  130. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  131. else:
  132. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  133. return fullPath
  134. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  135. #@param: raw url as crawler crawls through every site
  136. def getNameFromURL(url):
  137. global counter
  138. name = ''.join(e for e in url if e.isalnum())
  139. if (name == ''):
  140. name = str(counter)
  141. counter = counter + 1
  142. return name
  143. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  144. #in this example, there are a couple of categories some threads fall under such as
  145. # Guides and Tutorials, Digital Products, and Software and Malware
  146. #as you can see they are categories of products
  147. def getInterestedLinks():
  148. links = []
  149. # software and malware
  150. links.append('http://mdbvvcfwl3fpckiraucv7gio57yoslnhfjxzpoihf4fgdkdd7bwyv7id.onion/products/softwares-and-malwares')
  151. # guides and tutorials
  152. links.append('http://mdbvvcfwl3fpckiraucv7gio57yoslnhfjxzpoihf4fgdkdd7bwyv7id.onion/products/guides-and-tutorials')
  153. # services
  154. links.append('http://mdbvvcfwl3fpckiraucv7gio57yoslnhfjxzpoihf4fgdkdd7bwyv7id.onion/products/services')
  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 MetaVerse 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(baseURL, 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. #
  188. # # comment out
  189. # if count == 1:
  190. # break
  191. try:
  192. link = driver.find_element(by=By.PARTIAL_LINK_TEXT, value='Next').get_attribute('href')
  193. if link.endswith('#') or link == "":
  194. raise NoSuchElementException
  195. count += 1
  196. except NoSuchElementException:
  197. has_next_page = False
  198. except Exception as e:
  199. print(link, e)
  200. i += 1
  201. print("Crawling the MetaVerse market done.")
  202. # Returns 'True' if the link is a description link
  203. #@param: url of any url crawled
  204. #return: true if is a description page, false if not
  205. def isDescriptionLink(url):
  206. if 'PR' in url:
  207. return True
  208. return False
  209. # Returns True if the link is a listingPage link
  210. #@param: url of any url crawled
  211. #return: true if is a Listing page, false if not
  212. def isListingLink(url):
  213. if 'products' in url:
  214. return True
  215. return False
  216. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  217. #@param: link from interested link list ie. getInterestingLinks()
  218. #return: list of description links that should be crawled through
  219. def productPages(html):
  220. soup = BeautifulSoup(html, "html.parser")
  221. return metaversemarket_links_parser(soup)
  222. # Drop links that "signout"
  223. # def isSignOut(url):
  224. # #absURL = urlparse.urljoin(url.base_url, url.url)
  225. # if 'signout' in url.lower() or 'logout' in url.lower():
  226. # return True
  227. #
  228. # return False
  229. def crawler():
  230. startCrawling()
  231. # print("Crawling and Parsing MetaVerseMarket .... DONE!")