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.

330 lines
10 KiB

  1. __author__ = 'cern'
  2. '''
  3. BlackPyramid Market 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.common.by import By
  11. from selenium.webdriver.support import expected_conditions as EC
  12. from selenium.webdriver.support.ui import WebDriverWait
  13. from selenium.webdriver import ActionChains
  14. import selenium.webdriver.support.ui as uiClasses
  15. from selenium.webdriver.common.keys import Keys
  16. from PIL import Image
  17. import urllib.parse as urlparse
  18. import os, re, time
  19. import subprocess
  20. import configparser
  21. from bs4 import BeautifulSoup
  22. from MarketPlaces.Initialization.prepare_parser import new_parse
  23. from MarketPlaces.BlackPyramid.parser import BlackPyramid_links_parser
  24. from MarketPlaces.Utilities.utilities import cleanHTML
  25. import traceback
  26. counter = 1
  27. baseURL = 'http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/'
  28. # Opens Tor Browser, crawls the website
  29. def startCrawling():
  30. marketName = 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(marketName, baseURL, True)
  40. # Login
  41. def login(driver):
  42. # wait for login page
  43. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  44. (By.XPATH, "//input[@name='username_login']")))
  45. # entering username and password into input boxes
  46. usernameBox = driver.find_element(by=By.XPATH, value="//input[@name='username_login']")
  47. # Username here
  48. usernameBox.send_keys('ChipotleSteakBurrito')
  49. passwordBox = driver.find_element(by=By.XPATH, value="//input[@name='password_login']")
  50. # Password here
  51. passwordBox.send_keys('BlackBeans')
  52. input("Press ENTER when CAPTCHA is completed and you closed the newsletter\n")
  53. # wait for listing page show up (This Xpath may need to change based on different seed url)
  54. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  55. (By.XPATH, '//*[@id="form93b"]')))
  56. # Returns the name of the website
  57. def getMKTName():
  58. name = 'BlackPyramid'
  59. return name
  60. # Return the link of the website
  61. def getFixedURL():
  62. url = 'http://blackpyoc3gbnrlvxqvvytd3kxqj7pd226i2gvfyhysj24ne2snkmnyd.onion/login/?login=1'
  63. return url
  64. # Closes Tor Browser
  65. def closetor(driver):
  66. # global pid
  67. # os.system("taskkill /pid " + str(pro.pid))
  68. # os.system("taskkill /t /f /im tor.exe")
  69. print('Closing Tor...')
  70. driver.close()
  71. time.sleep(3)
  72. return
  73. # Creates FireFox 'driver' and configure its 'Profile'
  74. # to use Tor proxy and socket
  75. def createFFDriver():
  76. from MarketPlaces.Initialization.markets_mining import config
  77. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  78. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  79. ff_prof.set_preference("places.history.enabled", False)
  80. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  81. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  82. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  83. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  84. ff_prof.set_preference("signon.rememberSignons", False)
  85. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  86. # ff_prof.set_preference("network.dns.disablePrefetch", True)
  87. # ff_prof.set_preference("network.http.sendRefererHeader", 0)
  88. ff_prof.set_preference("permissions.default.image", 3)
  89. ff_prof.set_preference("browser.download.folderList", 2)
  90. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  91. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  92. ff_prof.set_preference('network.proxy.type', 1)
  93. ff_prof.set_preference("network.proxy.socks_version", 5)
  94. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  95. ff_prof.set_preference('network.proxy.socks_port', 9150)
  96. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  97. ff_prof.set_preference("javascript.enabled", False)
  98. ff_prof.update_preferences()
  99. service = Service(config.get('TOR', 'geckodriver_path'))
  100. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  101. driver.maximize_window()
  102. return driver
  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. # Saves the crawled html page
  113. def savePage(driver, page, url):
  114. cleanPage = cleanHTML(driver, page)
  115. filePath = getFullPathName(url)
  116. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  117. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  118. return
  119. # Gets the full path of the page to be saved along with its appropriate file name
  120. def getFullPathName(url):
  121. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  122. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  123. fileName = getNameFromURL(url)
  124. if isDescriptionLink(url):
  125. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  126. else:
  127. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  128. return fullPath
  129. # Creates the file name from passed URL
  130. def getNameFromURL(url):
  131. global counter
  132. name = ''.join(e for e in url if e.isalnum())
  133. if name == '':
  134. name = str(counter)
  135. counter = counter + 1
  136. return name
  137. def page_is_fully_loaded(driver):
  138. return driver.execute_script("return document.readyState") == "complete"
  139. def goToPage(driver, page):
  140. # hover over digital -> hacking tools
  141. a = ActionChains(driver)
  142. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  143. (By.XPATH, "//li[@class='dig940']/div/a")))
  144. # hover
  145. digitalB = driver.find_element(By.XPATH, "//li[@class='dig940']/div/a")
  146. time.sleep(1)
  147. a.move_to_element(digitalB).perform()
  148. # print(digitalB)
  149. # delay for website to register hover
  150. time.sleep(5)
  151. # click
  152. xpath = "//input[@name='" + page + "']"
  153. link = driver.find_element(By.XPATH, xpath)
  154. time.sleep(1)
  155. a.move_to_element(link).click().perform()
  156. # print(link)
  157. # wait for website to load
  158. time.sleep(10)
  159. WebDriverWait(driver, 100).until(page_is_fully_loaded)
  160. def getInterestedLinks():
  161. links = []
  162. # h11 -> Hacking Tools
  163. links.append('h11')
  164. # g3 -> Guides, Hacking
  165. links.append('g3')
  166. # se3 -> Services
  167. links.append('se11')
  168. # f6 -> Fraud
  169. links.append('f11')
  170. return links
  171. def crawlForum(driver):
  172. print("Crawling the BlackPyramid market")
  173. pages = getInterestedLinks()
  174. i = 0
  175. for listing in pages:
  176. print('Crawling :', listing)
  177. try:
  178. driver.get(baseURL)
  179. goToPage(driver, listing)
  180. has_next_page = True
  181. count = 0
  182. currentPage = 1
  183. while has_next_page:
  184. html = driver.page_source
  185. savePage(driver, html, listing + "page" + str(currentPage))
  186. # get a list of urls for each listing
  187. list = productPages(html)
  188. for item in list:
  189. itemURL = urlparse.urljoin(baseURL, str(item))
  190. try:
  191. driver.get(itemURL)
  192. except:
  193. # driver.refresh()
  194. continue
  195. savePage(driver, driver.page_source, item)
  196. # can't use the back button in dark pyramid
  197. # driver.back()
  198. # # comment out
  199. # break
  200. #
  201. # # comment out
  202. # if count == 1:
  203. # break
  204. # go to next page of market
  205. try:
  206. # Scroll to top of page to see navigation bar
  207. driver.find_element(by=By.XPATH, value="//body").send_keys(Keys.CONTROL + Keys.HOME)
  208. goToPage(driver, listing)
  209. nav = driver.find_element(by=By.XPATH, value="//input[@name='next_page']")
  210. if nav.is_enabled():
  211. # select next page
  212. pgnum = uiClasses.Select(driver.find_element(by=By.XPATH, value="//select[@name='pageination']"))
  213. # print("pg options:", pgnum.options)
  214. numberOfPages = len(pgnum.options)
  215. if currentPage >= numberOfPages:
  216. raise NoSuchElementException
  217. pgnum.select_by_index(currentPage)
  218. currentPage += 1
  219. # click button
  220. pgbutton = driver.find_element(by=By.XPATH, value="//input[@value='go to page']")
  221. pgbutton.click()
  222. # wait for website to load
  223. time.sleep(10)
  224. WebDriverWait(driver, 100).until(page_is_fully_loaded)
  225. else:
  226. raise NoSuchElementException
  227. count += 1
  228. except NoSuchElementException:
  229. has_next_page = False
  230. except Exception as e:
  231. print(listing, e)
  232. i += 1
  233. print("Crawling the BlackPyramid market done.")
  234. # Returns 'True' if the link is Topic link
  235. def isDescriptionLink(url):
  236. if 'product' in url:
  237. return True
  238. return False
  239. # Returns True if the link is a listingPage link
  240. def isListingLink(url):
  241. if 'category=' in url:
  242. return True
  243. return False
  244. # calling the parser to define the links
  245. def productPages(html):
  246. soup = BeautifulSoup(html, "html.parser")
  247. return BlackPyramid_links_parser(soup)
  248. def crawler():
  249. startCrawling()
  250. # print("Crawling and Parsing BestCardingWorld .... DONE!")