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.

268 lines
8.3 KiB

  1. __author__ = 'DarkWeb'
  2. '''
  3. PabloEscobarMarket 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.common.by import By
  11. from selenium.webdriver.support import expected_conditions as EC
  12. from selenium.webdriver.support.ui import WebDriverWait
  13. from PIL import Image
  14. import urllib.parse as urlparse
  15. import os, re, time
  16. import subprocess
  17. from bs4 import BeautifulSoup
  18. from MarketPlaces.Initialization.prepare_parser import new_parse
  19. from MarketPlaces.PabloEscobarMarket.parser import pabloescobarmarket_links_parser
  20. from MarketPlaces.Utilities.utilities import cleanHTML
  21. counter = 1
  22. baseURL = 'http://niejmptjzwhlfywruoab4pbuxg7kp2mtcr4c6mgpeykju5matewg36yd.onion/'
  23. # Opens Tor Browser, crawls the website
  24. def startCrawling():
  25. # opentor()
  26. mktName = getMKTName()
  27. driver = getAccess()
  28. if driver != 'down':
  29. try:
  30. login(driver)
  31. crawlForum(driver)
  32. except Exception as e:
  33. print(driver.current_url, e)
  34. closetor(driver)
  35. new_parse(mktName, baseURL, True)
  36. # Opens Tor Browser
  37. def opentor():
  38. from MarketPlaces.Initialization.markets_mining import config
  39. global pid
  40. print("Connecting Tor...")
  41. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  42. pid = pro.pid
  43. time.sleep(7.5)
  44. input('Tor Connected. Press ENTER to continue\n')
  45. return
  46. # Login using premade account credentials and do login captcha manually
  47. def login(driver):
  48. input("Press ENTER when CAPTCHA is complete and login page has loaded\n")
  49. # entering username and password into input boxes
  50. usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="username"]')
  51. # Username here
  52. usernameBox.send_keys('snorlaxrights')
  53. passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="inputPassword3"]')
  54. # Password here
  55. passwordBox.send_keys('$noringAllday')
  56. input("Press ENTER when CAPTCHA is completed\n")
  57. # wait for listing page show up (This Xpath may need to change based on different seed url)
  58. # wait for 50 sec until id = tab_content is found, then cont
  59. WebDriverWait(driver, 50).until(EC.visibility_of_element_located(
  60. (By.XPATH, '//*[@id="collapse3"]')))
  61. # Returns the name of the website
  62. def getMKTName() -> str:
  63. name = 'PabloEscobarMarket'
  64. return name
  65. # Return the link of the website
  66. def getFixedURL():
  67. url = 'http://niejmptjzwhlfywruoab4pbuxg7kp2mtcr4c6mgpeykju5matewg36yd.onion/'
  68. return url
  69. # Closes Tor Browser
  70. def closetor(driver):
  71. # global pid
  72. # os.system("taskkill /pid " + str(pro.pid))
  73. # os.system("taskkill /t /f /im tor.exe")
  74. print('Closing Tor...')
  75. driver.close() #close tab
  76. time.sleep(3)
  77. return
  78. # Creates FireFox 'driver' and configure its 'Profile'
  79. # to use Tor proxy and socket
  80. def createFFDriver():
  81. from MarketPlaces.Initialization.markets_mining import config
  82. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  83. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  84. ff_prof.set_preference("places.history.enabled", False)
  85. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  86. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  87. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  88. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  89. ff_prof.set_preference("signon.rememberSignons", False)
  90. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  91. ff_prof.set_preference("network.dns.disablePrefetch", True)
  92. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  93. ff_prof.set_preference("permissions.default.image", 3)
  94. ff_prof.set_preference("browser.download.folderList", 2)
  95. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  96. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  97. ff_prof.set_preference('network.proxy.type', 1)
  98. ff_prof.set_preference("network.proxy.socks_version", 5)
  99. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  100. ff_prof.set_preference('network.proxy.socks_port', 9150)
  101. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  102. ff_prof.set_preference("javascript.enabled", True)
  103. ff_prof.update_preferences()
  104. service = Service(config.get('TOR', 'geckodriver_path'))
  105. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  106. return driver
  107. def getAccess():
  108. url = getFixedURL()
  109. driver = createFFDriver()
  110. try:
  111. driver.get(url)
  112. return driver
  113. except:
  114. driver.close()
  115. return 'down'
  116. # Saves the crawled html page
  117. def savePage(driver, page, url):
  118. cleanPage = cleanHTML(driver, page)
  119. filePath = getFullPathName(url)
  120. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  121. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  122. return
  123. # Gets the full path of the page to be saved along with its appropriate file name
  124. def getFullPathName(url):
  125. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  126. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  127. fileName = getNameFromURL(url)
  128. if isDescriptionLink(url):
  129. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  130. else:
  131. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  132. return fullPath
  133. # Creates the file name from passed URL
  134. def getNameFromURL(url):
  135. global counter
  136. name = ''.join(e for e in url if e.isalnum())
  137. if name == '':
  138. name = str(counter)
  139. counter = counter + 1
  140. return name
  141. # FIX
  142. def getInterestedLinks():
  143. links = []
  144. # hire hacker
  145. links.append('http://niejmptjzwhlfywruoab4pbuxg7kp2mtcr4c6mgpeykju5matewg36yd.onion/?sub_id=36')
  146. # hacker
  147. links.append('http://niejmptjzwhlfywruoab4pbuxg7kp2mtcr4c6mgpeykju5matewg36yd.onion/?sub_id=34')
  148. return links
  149. def crawlForum(driver):
  150. print("Crawling the PabloEscobarMarket market")
  151. linksToCrawl = getInterestedLinks()
  152. i = 0
  153. while i < len(linksToCrawl):
  154. link = linksToCrawl[i]
  155. print('Crawling :', link)
  156. try:
  157. has_next_page = True
  158. count = 0
  159. while has_next_page:
  160. try:
  161. driver.get(link)
  162. except:
  163. driver.refresh()
  164. html = driver.page_source
  165. savePage(driver, html, link)
  166. list = productPages(html)
  167. for item in list:
  168. itemURL = urlparse.urljoin(baseURL, str(item))
  169. try:
  170. driver.get(itemURL)
  171. except:
  172. driver.refresh()
  173. savePage(driver, driver.page_source, item)
  174. driver.back()
  175. # comment out
  176. break
  177. # comment out
  178. if count == 1:
  179. break
  180. try:
  181. link = driver.find_element(by=By.XPATH, value='//a[@rel="next"]').get_attribute('href')
  182. if link == "":
  183. raise NoSuchElementException
  184. count += 1
  185. except NoSuchElementException:
  186. has_next_page = False
  187. except Exception as e:
  188. print(link, e)
  189. i += 1
  190. print("Crawling the PabloEscobarMarket market done.")
  191. # Returns 'True' if the link is Topic link, may need to change for every website
  192. def isDescriptionLink(url):
  193. if 'single_product' in url:
  194. return True
  195. return False
  196. # Returns True if the link is a listingPage link, may need to change for every website
  197. def isListingLink(url):
  198. if 'sub_id' in url:
  199. return True
  200. return False
  201. # calling the parser to define the links
  202. def productPages(html):
  203. soup = BeautifulSoup(html, "html.parser")
  204. return pabloescobarmarket_links_parser(soup)
  205. def crawler():
  206. startCrawling()
  207. # print("Crawling and Parsing PabloEscobarMarket .... DONE!")