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.

263 lines
8.3 KiB

  1. __author__ = 'DarkWeb'
  2. '''
  3. Sonanza 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.Sonanza.parser import sonanza_links_parser
  23. from MarketPlaces.Utilities.utilities import cleanHTML
  24. counter = 1
  25. baseURL = 'http://sonanzazddbd3lqw2ai6uwmnb4fx7tj7h6hmdwkfqe7bnzgpuvkxqpyd.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 = 'Sonanza'
  40. return name
  41. # Return the base link of the website
  42. def getFixedURL():
  43. url = 'http://sonanzazddbd3lqw2ai6uwmnb4fx7tj7h6hmdwkfqe7bnzgpuvkxqpyd.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. #
  97. # # entering username and password into input boxes
  98. # usernameBox = driver.find_element(by=By.XPATH, value='//input[@name="username"]')
  99. # # Username here
  100. # usernameBox.send_keys('aliciamykeys')
  101. # passwordBox = driver.find_element(by=By.XPATH, value='//input[@name="password"]')
  102. # # Password here
  103. # passwordBox.send_keys('aliciawherearemykey$')
  104. # # session time
  105. # 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'))
  106. # session_select.select_by_visible_text('Session 60min')
  107. input("Press ENTER when CAPTCHA is completed and listing page loaded\n")
  108. # wait for listing page show up (This Xpath may need to change based on different seed url)
  109. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  110. (By.XPATH, '//*[@id="searchbar"]')))
  111. def savePage(driver, page, url):
  112. cleanPage = cleanHTML(driver, page)
  113. filePath = getFullPathName(url)
  114. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  115. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  116. return
  117. def getFullPathName(url):
  118. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  119. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  120. fileName = getNameFromURL(url)
  121. if isDescriptionLink(url):
  122. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  123. else:
  124. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  125. return fullPath
  126. def getNameFromURL(url):
  127. global counter
  128. name = ''.join(e for e in url if e.isalnum())
  129. if name == '':
  130. name = str(counter)
  131. counter = counter + 1
  132. return name
  133. def getInterestedLinks():
  134. links = []
  135. # Guides and Tutorials
  136. links.append('http://sonanzazddbd3lqw2ai6uwmnb4fx7tj7h6hmdwkfqe7bnzgpuvkxqpyd.onion/category/3')
  137. # Software and Malware
  138. links.append('http://sonanzazddbd3lqw2ai6uwmnb4fx7tj7h6hmdwkfqe7bnzgpuvkxqpyd.onion/category/4')
  139. # Fraud
  140. links.append('http://sonanzazddbd3lqw2ai6uwmnb4fx7tj7h6hmdwkfqe7bnzgpuvkxqpyd.onion/category/5')
  141. # Digital Products
  142. links.append('http://sonanzazddbd3lqw2ai6uwmnb4fx7tj7h6hmdwkfqe7bnzgpuvkxqpyd.onion/category/21')
  143. # Services
  144. links.append('http://sonanzazddbd3lqw2ai6uwmnb4fx7tj7h6hmdwkfqe7bnzgpuvkxqpyd.onion/category/22')
  145. return links
  146. def crawlForum(driver):
  147. print("Crawling the Sonanza market")
  148. linksToCrawl = getInterestedLinks()
  149. i = 0
  150. while i < len(linksToCrawl):
  151. link = linksToCrawl[i]
  152. print('Crawling :', link)
  153. try:
  154. has_next_page = True
  155. count = 0
  156. while has_next_page:
  157. try:
  158. driver.get(link)
  159. except:
  160. driver.refresh()
  161. html = driver.page_source
  162. savePage(driver, html, link)
  163. list = productPages(html)
  164. for item in list:
  165. itemURL = urlparse.urljoin(baseURL, str(item))
  166. try:
  167. driver.get(itemURL)
  168. except:
  169. driver.refresh()
  170. savePage(driver, driver.page_source, item)
  171. driver.back()
  172. # # comment out
  173. # break
  174. #
  175. # # comment out
  176. # if count == 1:
  177. # break
  178. try:
  179. link = driver.find_element(by=By.XPATH, value='//a[contains(text(), "")]').get_attribute('href')
  180. if link == "":
  181. raise NoSuchElementException
  182. count += 1
  183. except NoSuchElementException:
  184. has_next_page = False
  185. except Exception as e:
  186. print(link, e)
  187. i += 1
  188. print("Crawling the Sonanza market done.")
  189. # Returns 'True' if the link is Topic link, may need to change for every website
  190. def isDescriptionLink(url):
  191. if 'article' in url:
  192. return True
  193. return False
  194. # Returns True if the link is a listingPage link, may need to change for every website
  195. def isListingLink(url):
  196. if 'category' in url:
  197. return True
  198. return False
  199. def productPages(html):
  200. soup = BeautifulSoup(html, "html.parser")
  201. return sonanza_links_parser(soup)
  202. def crawler():
  203. startCrawling()