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.

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