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.

276 lines
8.4 KiB

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