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.

298 lines
9.9 KiB

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