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.

329 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, False)
  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. # h11 -> Hacking Tools
  162. # g3 -> Guides, Hacking
  163. # se3 -> Services, Hacking
  164. # f6 -> Fraud software
  165. links = ['h11','g3','se3','f6']
  166. return links
  167. def crawlForum(driver):
  168. print("Crawling the BlackPyramid market")
  169. pages = getInterestedLinks()
  170. i = 0
  171. for listing in pages:
  172. print('Crawling :', listing)
  173. try:
  174. goToPage(driver, listing)
  175. has_next_page = True
  176. count = 0
  177. currentPage = 1
  178. while has_next_page:
  179. html = driver.page_source
  180. savePage(driver, html, listing + "page" + str(currentPage))
  181. # get a list of urls for each listing
  182. list = productPages(html)
  183. for item in list:
  184. itemURL = urlparse.urljoin(baseURL, str(item))
  185. try:
  186. driver.get(itemURL)
  187. except:
  188. # driver.refresh()
  189. continue
  190. savePage(driver, driver.page_source, item)
  191. # can't use the back button in dark pyramid
  192. # driver.back()
  193. # comment out
  194. break
  195. # comment out
  196. if count == 1:
  197. break
  198. # go to next page of market
  199. try:
  200. # Scroll to top of page to see navigation bar
  201. driver.find_element(by=By.XPATH, value="//body").send_keys(Keys.CONTROL + Keys.HOME)
  202. goToPage(driver, listing)
  203. nav = driver.find_element(by=By.XPATH, value="//input[@name='next_page']")
  204. if nav.is_enabled():
  205. # select next page
  206. pgnum = uiClasses.Select(driver.find_element(by=By.XPATH, value="//select[@name='pageination']"))
  207. # print("pg options:", pgnum.options)
  208. numberOfPages = len(pgnum.options)
  209. if currentPage >= numberOfPages:
  210. raise NoSuchElementException
  211. pgnum.select_by_index(currentPage)
  212. currentPage += 1
  213. # click button
  214. pgbutton = driver.find_element(by=By.XPATH, value="//input[@value='go to page']")
  215. pgbutton.click()
  216. # wait for website to load
  217. time.sleep(10)
  218. WebDriverWait(driver, 100).until(page_is_fully_loaded)
  219. else:
  220. raise NoSuchElementException
  221. count += 1
  222. except NoSuchElementException:
  223. has_next_page = False
  224. except Exception as e:
  225. print(listing, e)
  226. i += 1
  227. print("Crawling the BlackPyramid market done.")
  228. # Returns 'True' if the link is Topic link
  229. def isDescriptionLink(url):
  230. if 'product' in url:
  231. return True
  232. return False
  233. # Returns True if the link is a listingPage link
  234. def isListingLink(url):
  235. if 'category=' in url:
  236. return True
  237. return False
  238. # calling the parser to define the links
  239. def productPages(html):
  240. soup = BeautifulSoup(html, "html.parser")
  241. return BlackPyramid_links_parser(soup)
  242. def crawler():
  243. startCrawling()
  244. # print("Crawling and Parsing BestCardingWorld .... DONE!")
  245. if __name__ == "__main__":
  246. #crawler()
  247. new_parse("BlackPyramid", baseURL, False)