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.

262 lines
8.0 KiB

1 year ago
  1. __author__ = 'DarkWeb'
  2. '''
  3. DarkBazar 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.ui import Select
  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.DarkBazar.parser import darkbazar_links_parser
  23. from MarketPlaces.Utilities.utilities import cleanHTML
  24. counter = 1
  25. baseURL = 'http://jw5e5sdywqupaqgtt43uq5ysfqpd2vzefl65s2fcjlj4qfxivynv6bqd.onion/'
  26. def startCrawling():
  27. mktName = getMKTName()
  28. driver = getAccess()
  29. if driver != 'down':
  30. try:
  31. login(driver)
  32. crawlForum(driver)
  33. except Exception as e:
  34. print(driver.current_url, e)
  35. closeDriver(driver)
  36. new_parse(mktName, baseURL, True)
  37. # Returns the name of the website
  38. def getMKTName():
  39. name = 'DarkBazar'
  40. return name
  41. # Return the base link of the website
  42. def getFixedURL():
  43. url = 'http://jw5e5sdywqupaqgtt43uq5ysfqpd2vzefl65s2fcjlj4qfxivynv6bqd.onion/'
  44. return url
  45. # Closes Tor Browser
  46. def closeDriver(driver):
  47. # global pid
  48. # os.system("taskkill /pid " + str(pro.pid))
  49. # os.system("taskkill /t /f /im tor.exe")
  50. print('Closing Tor...')
  51. driver.close()
  52. time.sleep(3)
  53. return
  54. # Creates FireFox 'driver' and configure its 'Profile'
  55. # to use Tor proxy and socket
  56. def createFFDriver():
  57. from MarketPlaces.Initialization.markets_mining import config
  58. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  59. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  60. ff_prof.set_preference("places.history.enabled", False)
  61. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  62. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  63. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  64. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  65. ff_prof.set_preference("signon.rememberSignons", False)
  66. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  67. # ff_prof.set_preference("network.dns.disablePrefetch", True)
  68. # ff_prof.set_preference("network.http.sendRefererHeader", 0)
  69. ff_prof.set_preference("permissions.default.image", 3)
  70. ff_prof.set_preference("browser.download.folderList", 2)
  71. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  72. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  73. ff_prof.set_preference('network.proxy.type', 1)
  74. ff_prof.set_preference("network.proxy.socks_version", 5)
  75. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  76. ff_prof.set_preference('network.proxy.socks_port', 9150)
  77. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  78. ff_prof.set_preference("javascript.enabled", False)
  79. ff_prof.update_preferences()
  80. service = Service(config.get('TOR', 'geckodriver_path'))
  81. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  82. driver.maximize_window()
  83. return driver
  84. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  85. def getAccess():
  86. url = getFixedURL()
  87. driver = createFFDriver()
  88. try:
  89. driver.get(url)
  90. return driver
  91. except:
  92. driver.close()
  93. return 'down'
  94. def login(driver):
  95. input("Press ENTER when CAPTCHA is complete and login page has loaded\n")
  96. # entering username and password into input boxes
  97. usernameBox = driver.find_element(by=By.XPATH, value='//input[@name="username"]')
  98. # Username here
  99. usernameBox.send_keys('aliciamykeys')
  100. passwordBox = driver.find_element(by=By.XPATH, value='//input[@name="password"]')
  101. # Password here
  102. passwordBox.send_keys('aliciawherearemykey$')
  103. # session time
  104. session_select = Select(driver.find_element(by=By.XPATH, value='/html/body/main/div/div/div/div/div/form/div[4]/div/div[2]/select'))
  105. session_select.select_by_visible_text('Session 60min')
  106. input("Press ENTER when CAPTCHA is completed and you exit the newsletter\n")
  107. # wait for listing page show up (This Xpath may need to change based on different seed url)
  108. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  109. (By.XPATH, '//*[@id="submit"]')))
  110. def savePage(driver, page, url):
  111. cleanPage = cleanHTML(driver, page)
  112. filePath = getFullPathName(url)
  113. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  114. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  115. return
  116. def getFullPathName(url):
  117. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  118. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  119. fileName = getNameFromURL(url)
  120. if isDescriptionLink(url):
  121. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  122. else:
  123. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  124. return fullPath
  125. def getMKTName() -> str:
  126. name = 'DarkBazar'
  127. return name
  128. def getNameFromURL(url):
  129. global counter
  130. name = ''.join(e for e in url if e.isalnum())
  131. if name == '':
  132. name = str(counter)
  133. counter = counter + 1
  134. return name
  135. def getInterestedLinks():
  136. links = []
  137. # Digital Goods
  138. links.append('http://jw5e5sdywqupaqgtt43uq5ysfqpd2vzefl65s2fcjlj4qfxivynv6bqd.onion/cat.php?category=3')
  139. # Services
  140. links.append('http://jw5e5sdywqupaqgtt43uq5ysfqpd2vzefl65s2fcjlj4qfxivynv6bqd.onion/cat.php?category=5')
  141. return links
  142. def crawlForum(driver):
  143. print("Crawling the DarkBazar market")
  144. linksToCrawl = getInterestedLinks()
  145. i = 0
  146. while i < len(linksToCrawl):
  147. link = linksToCrawl[i]
  148. print('Crawling :', link)
  149. try:
  150. has_next_page = True
  151. count = 0
  152. while has_next_page:
  153. try:
  154. driver.get(link)
  155. except:
  156. driver.refresh()
  157. html = driver.page_source
  158. savePage(driver, html, link)
  159. list = productPages(html)
  160. for item in list:
  161. itemURL = urlparse.urljoin(baseURL, str(item))
  162. try:
  163. driver.get(itemURL)
  164. except:
  165. driver.refresh()
  166. savePage(driver, driver.page_source, item)
  167. driver.back()
  168. # comment out
  169. break
  170. # comment out
  171. if count == 1:
  172. break
  173. try:
  174. link = driver.find_element(by=By.XPATH, value='//a[contains(text(), "Next")]').get_attribute('href')
  175. if link == "":
  176. raise NoSuchElementException
  177. count += 1
  178. except NoSuchElementException:
  179. has_next_page = False
  180. except Exception as e:
  181. print(link, e)
  182. i += 1
  183. print("Crawling the DarkBazar market done.")
  184. # Returns 'True' if the link is Topic link, may need to change for every website
  185. def isDescriptionLink(url):
  186. if 'item' in url:
  187. return True
  188. return False
  189. # Returns True if the link is a listingPage link, may need to change for every website
  190. def isListingLink(url):
  191. if 'category=' in url:
  192. return True
  193. return False
  194. def productPages(html):
  195. soup = BeautifulSoup(html, "html.parser")
  196. return darkbazar_links_parser(soup)
  197. def crawler():
  198. startCrawling()