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.

293 lines
10 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. '''
  3. CypherMarketplace Forum Crawler (Selenium)
  4. crawler done
  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.CypherMarketplace.parser import cyphermarketplace_links_parser
  23. from MarketPlaces.Utilities.utilities import cleanHTML
  24. counter = 1
  25. baseURL = 'http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.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. mktName = getMKTName()
  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(mktName, baseURL, True)
  39. # Returns the name of the website
  40. #return: name of site in string type
  41. def getMKTName():
  42. name = 'CypherMarketplace'
  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://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.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. url = getFixedURL()
  93. driver = createFFDriver()
  94. try:
  95. driver.get(url)
  96. return driver
  97. except:
  98. driver.close()
  99. return 'down'
  100. # Manual captcha solver, waits fora specific element so that the whole page loads, finds the input box, gets screenshot of captcha
  101. # then allows for manual solving of captcha in the terminal
  102. #@param: current selenium web driver
  103. def login(driver):
  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, "/html/body/div/div[1]/div/div[1]/div[1]/ul")))
  107. # entering username and password into input boxes
  108. usernameBox = driver.find_element(by=By.XPATH, value='/html/body/div/div[2]/div/form/table/tbody/tr[2]/td[2]/input')
  109. # Username here
  110. usernameBox.send_keys('beachyoga278') # sends string to the username box
  111. passwordBox = driver.find_element(by=By.XPATH, value='/html/body/div/div[2]/div/form/table/tbody/tr[3]/td[2]/input')
  112. # Password here
  113. passwordBox.send_keys('sunfish278') # sends string to passwordBox
  114. input("Press ENTER when CAPTCHA is completed\n")
  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[2]/div/div/div[1]/div/div/div[1]/div[2]/ul/li[8]/a")))
  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/" + getMKTName() + "/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://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/040ca140-3cfc-11ea-9364-87edd8c0a63f')
  153. # # guides
  154. # links.append('http://6c5qa2ke2esh6ake6u6yoxjungz2czbbl7hqxl75v5k37frtzhxuk7ad.onion/category/35a35d10-3cfb-11ea-9b14-65b8930c1372')
  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 CypherMarketplace 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. # comment out
  188. if count == 1:
  189. break
  190. try:
  191. temp = driver.find_element(by=By.XPATH, value=
  192. '/html/body/div[2]/div/div/div[2]/div/nav/ul')
  193. link = temp.find_element(by=By.TAG_NAME, value='page-link').get_attribute('href')
  194. if link == "":
  195. raise NoSuchElementException
  196. count += 1
  197. except NoSuchElementException:
  198. has_next_page = False
  199. except Exception as e:
  200. print(link, e)
  201. i += 1
  202. print("Crawling the CypherMarketplace market done.")
  203. # Returns 'True' if the link is a description link
  204. #@param: url of any url crawled
  205. #return: true if is a description page, false if not
  206. def isDescriptionLink(url):
  207. if 'product' in url:
  208. return True
  209. return False
  210. # Returns True if the link is a listingPage link
  211. #@param: url of any url crawled
  212. #return: true if is a Listing page, false if not
  213. def isListingLink(url):
  214. if 'category' in url:
  215. return True
  216. return False
  217. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  218. #@param: link from interested link list ie. getInterestingLinks()
  219. #return: list of description links that should be crawled through
  220. def productPages(html):
  221. soup = BeautifulSoup(html, "html.parser")
  222. return cyphermarketplace_links_parser(soup)
  223. # Drop links that "signout"
  224. # def isSignOut(url):
  225. # #absURL = urlparse.urljoin(url.base_url, url.url)
  226. # if 'signout' in url.lower() or 'logout' in url.lower():
  227. # return True
  228. #
  229. # return False
  230. def crawler():
  231. startCrawling()
  232. # print("Crawling and Parsing BestCardingWorld .... DONE!")