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.

295 lines
9.9 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. '''
  3. AnonymousMarketplace Marketplace Crawler (Selenium)
  4. this is a small marketplace so next page links are not coded in
  5. '''
  6. from selenium import webdriver
  7. from selenium.common.exceptions import NoSuchElementException
  8. from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
  9. from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
  10. from selenium.webdriver.firefox.service import Service
  11. from selenium.webdriver.support.ui import WebDriverWait
  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.AnonymousMarketplace.parser import anonymous_links_parser
  23. from MarketPlaces.Utilities.utilities import cleanHTML
  24. counter = 1
  25. baseURL = 'http://3fqr7fgjaslhgmeiin5e2ky6ra5xkiafyzg7i36sfcehv3jvpgydteqd.onion/'
  26. # Opens Tor Browser, crawls the website, then parses, then closes tor
  27. #acts like the main method for the crawler, another function at the end of this code calls this function later
  28. def startCrawling():
  29. # opentor()
  30. mktName = getMKTName()
  31. driver = getAccess()
  32. if driver != 'down':
  33. try:
  34. # login(driver)
  35. crawlForum(driver)
  36. except Exception as e:
  37. print(driver.current_url, e)
  38. closetor(driver)
  39. new_parse(mktName, baseURL, True)
  40. # Opens Tor Browser
  41. #prompts for ENTER input to continue
  42. def opentor():
  43. from MarketPlaces.Initialization.markets_mining import config
  44. global pid
  45. print("Connecting Tor...")
  46. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  47. pid = pro.pid
  48. time.sleep(7.5)
  49. input('Tor Connected. Press ENTER to continue\n')
  50. return
  51. # Returns the name of the website
  52. #return: name of site in string type
  53. def getMKTName():
  54. name = 'AnonymousMarketplace'
  55. return name
  56. # Return the base link of the website
  57. #return: url of base site in string type
  58. def getFixedURL():
  59. url = 'http://3fqr7fgjaslhgmeiin5e2ky6ra5xkiafyzg7i36sfcehv3jvpgydteqd.onion/'
  60. return url
  61. # Closes Tor Browser
  62. #@param: current selenium driver
  63. def closetor(driver):
  64. # global pid
  65. # os.system("taskkill /pid " + str(pro.pid))
  66. # os.system("taskkill /t /f /im tor.exe")
  67. print('Closing Tor...')
  68. driver.close()
  69. time.sleep(3)
  70. return
  71. # Creates FireFox 'driver' and configure its 'Profile'
  72. # to use Tor proxy and socket
  73. def createFFDriver():
  74. from MarketPlaces.Initialization.markets_mining import config
  75. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  76. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  77. ff_prof.set_preference("places.history.enabled", False)
  78. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  79. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  80. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  81. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  82. ff_prof.set_preference("signon.rememberSignons", False)
  83. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  84. ff_prof.set_preference("network.dns.disablePrefetch", True)
  85. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  86. ff_prof.set_preference("permissions.default.image", 1)
  87. ff_prof.set_preference("browser.download.folderList", 2)
  88. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  89. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  90. ff_prof.set_preference('network.proxy.type', 1)
  91. ff_prof.set_preference("network.proxy.socks_version", 5)
  92. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  93. ff_prof.set_preference('network.proxy.socks_port', 9150)
  94. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  95. ff_prof.set_preference("javascript.enabled", False)
  96. ff_prof.update_preferences()
  97. service = Service(config.get('TOR', 'geckodriver_path'))
  98. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  99. driver.maximize_window()
  100. return driver
  101. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  102. #return: return the selenium driver or string 'down'
  103. def getAccess():
  104. url = getFixedURL()
  105. driver = createFFDriver()
  106. try:
  107. driver.get(url)
  108. return driver
  109. except:
  110. driver.close()
  111. return 'down'
  112. # Manual captcha solver, waits fora specific element so that the whole page loads, finds the input box, gets screenshot of captcha
  113. # then allows for manual solving of captcha in the terminal
  114. #@param: current selenium web driver
  115. def login(driver):
  116. # wait for page to show up (This Xpath may need to change based on different seed url)
  117. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  118. (By.ID, "woocommerce_product_categories-2")))
  119. # Saves the crawled html page, makes the directory path for html pages if not made
  120. def savePage(driver, page, url):
  121. cleanPage = cleanHTML(driver, page)
  122. filePath = getFullPathName(url)
  123. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  124. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  125. return
  126. # Gets the full path of the page to be saved along with its appropriate file name
  127. #@param: raw url as crawler crawls through every site
  128. def getFullPathName(url):
  129. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  130. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  131. fileName = getNameFromURL(url)
  132. if isDescriptionLink(url):
  133. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  134. else:
  135. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  136. return fullPath
  137. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  138. #@param: raw url as crawler crawls through every site
  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. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  147. #in this example, there are a couple of categories some threads fall under such as
  148. # Guides and Tutorials, Digital Products, and Software and Malware
  149. #as you can see they are categories of products
  150. def getInterestedLinks():
  151. links = []
  152. # # carding
  153. # links.append('http://3fqr7fgjaslhgmeiin5e2ky6ra5xkiafyzg7i36sfcehv3jvpgydteqd.onion/product-category/carding/')
  154. # # hacked paypal
  155. # links.append('http://3fqr7fgjaslhgmeiin5e2ky6ra5xkiafyzg7i36sfcehv3jvpgydteqd.onion/product-category/hacked-paypal-accounts/')
  156. # hacking services
  157. links.append('http://3fqr7fgjaslhgmeiin5e2ky6ra5xkiafyzg7i36sfcehv3jvpgydteqd.onion/product-category/hacking-services/')
  158. return links
  159. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  160. #topic and description pages are crawled through here, where both types of pages are saved
  161. #@param: selenium driver
  162. def crawlForum(driver):
  163. print("Crawling the AnonymousMarketplace market")
  164. linksToCrawl = getInterestedLinks()
  165. i = 0
  166. while i < len(linksToCrawl):
  167. link = linksToCrawl[i]
  168. print('Crawling :', link)
  169. try:
  170. has_next_page = True
  171. count = 0
  172. while has_next_page:
  173. try:
  174. driver.get(link)
  175. except:
  176. driver.refresh()
  177. html = driver.page_source
  178. savePage(driver, html, link)
  179. list = productPages(html)
  180. for item in list:
  181. itemURL = urlparse.urljoin(baseURL, str(item))
  182. try:
  183. driver.get(itemURL)
  184. except:
  185. driver.refresh()
  186. savePage(driver, driver.page_source, item)
  187. driver.back()
  188. # comment out
  189. break
  190. # comment out
  191. if count == 1:
  192. break
  193. #left in in case site changes
  194. try:
  195. link = ""
  196. if link == "":
  197. raise NoSuchElementException
  198. count += 1
  199. except NoSuchElementException:
  200. has_next_page = False
  201. except Exception as e:
  202. print(link, e)
  203. i += 1
  204. print("Crawling the AnonymousMarketplace market done.")
  205. # Returns 'True' if the link is a description link
  206. #@param: url of any url crawled
  207. #return: true if is a description page, false if not
  208. def isDescriptionLink(url):
  209. if '/product/' in url:
  210. return True
  211. return False
  212. # Returns True if the link is a listingPage link
  213. #@param: url of any url crawled
  214. #return: true if is a Listing page, false if not
  215. def isListingLink(url):
  216. if 'category' in url:
  217. return True
  218. return False
  219. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  220. #@param: link from interested link list ie. getInterestingLinks()
  221. #return: list of description links that should be crawled through
  222. def productPages(html):
  223. soup = BeautifulSoup(html, "html.parser")
  224. return anonymous_links_parser(soup)
  225. # Drop links that "signout"
  226. # def isSignOut(url):
  227. # #absURL = urlparse.urljoin(url.base_url, url.url)
  228. # if 'signout' in url.lower() or 'logout' in url.lower():
  229. # return True
  230. #
  231. # return False
  232. def crawler():
  233. startCrawling()
  234. # print("Crawling and Parsing BestCardingWorld .... DONE!")