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.

319 lines
11 KiB

  1. __author__ = 'Helium'
  2. '''
  3. CityMarket Marketplace Crawler (Selenium)
  4. not complete
  5. need to go through multiple pages...
  6. '''
  7. from selenium import webdriver
  8. from selenium.common.exceptions import NoSuchElementException
  9. from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
  10. from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
  11. from selenium.webdriver.firefox.service import Service
  12. from selenium.webdriver.support.ui import WebDriverWait
  13. from selenium.webdriver.support import expected_conditions as EC
  14. from selenium.webdriver.common.by import By
  15. from PIL import Image
  16. import urllib.parse as urlparse
  17. import os, re, time
  18. from datetime import date
  19. import subprocess
  20. import configparser
  21. from bs4 import BeautifulSoup
  22. from MarketPlaces.Initialization.prepare_parser import new_parse
  23. from MarketPlaces.CityMarket.parser import city_links_parser
  24. from MarketPlaces.Utilities.utilities import cleanHTML
  25. config = configparser.ConfigParser()
  26. config.read('../../setup.ini')
  27. counter = 1
  28. baseURL = 'http://wsptlnuoo3johqzcdlwuj5zcwfh2dwmswz6hahqctuxttvxpanypmwad.onion/'
  29. # Opens Tor Browser, crawls the website, then parses, then closes tor
  30. #acts like the main method for the crawler, another function at the end of this code calls this function later
  31. def startCrawling():
  32. opentor()
  33. # mktName = getMKTName()
  34. driver = getAccess()
  35. if driver != 'down':
  36. try:
  37. login(driver)
  38. crawlForum(driver)
  39. except Exception as e:
  40. print(driver.current_url, e)
  41. closetor(driver)
  42. # new_parse(forumName, baseURL, False)
  43. # Opens Tor Browser
  44. #prompts for ENTER input to continue
  45. def opentor():
  46. global pid
  47. print("Connecting Tor...")
  48. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  49. pid = pro.pid
  50. time.sleep(7.5)
  51. input('Tor Connected. Press ENTER to continue\n')
  52. return
  53. # Returns the name of the website
  54. #return: name of site in string type
  55. def getMKTName():
  56. name = 'CityMarket'
  57. return name
  58. # Return the base link of the website
  59. #return: url of base site in string type
  60. def getFixedURL():
  61. url = 'http://wsptlnuoo3johqzcdlwuj5zcwfh2dwmswz6hahqctuxttvxpanypmwad.onion/'
  62. return url
  63. # Closes Tor Browser
  64. #@param: current selenium driver
  65. def closetor(driver):
  66. # global pid
  67. # os.system("taskkill /pid " + str(pro.pid))
  68. # os.system("taskkill /t /f /im tor.exe")
  69. print('Closing Tor...')
  70. driver.close()
  71. time.sleep(3)
  72. return
  73. # Creates FireFox 'driver' and configure its 'Profile'
  74. # to use Tor proxy and socket
  75. def createFFDriver():
  76. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  77. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  78. ff_prof.set_preference("places.history.enabled", False)
  79. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  80. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  81. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  82. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  83. ff_prof.set_preference("signon.rememberSignons", False)
  84. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  85. ff_prof.set_preference("network.dns.disablePrefetch", True)
  86. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  87. ff_prof.set_preference("permissions.default.image", 1)##
  88. ff_prof.set_preference("browser.download.folderList", 2)
  89. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  90. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  91. ff_prof.set_preference('network.proxy.type', 1)
  92. ff_prof.set_preference("network.proxy.socks_version", 5)
  93. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  94. ff_prof.set_preference('network.proxy.socks_port', 9150)
  95. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  96. ff_prof.set_preference("javascript.enabled", False)
  97. ff_prof.update_preferences()
  98. service = Service(config.get('TOR', 'geckodriver_path'))
  99. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  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. input("Press ENTER when CAPTCHA is complete and login page has loaded\n")
  117. # entering username and password into input boxes
  118. usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="username"]')
  119. # Username here
  120. usernameBox.send_keys('findingmykeys')
  121. passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="inputPassword3"]')
  122. # Password here
  123. passwordBox.send_keys('ican’tFindMycarKey$')
  124. input("Press ENTER when CAPTCHA is completed and you exit the newsletter\n")
  125. # wait for listing page show up (This Xpath may need to change based on different seed url)
  126. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  127. (By.XPATH, '//*[@id="collapse3"]')))
  128. # Saves the crawled html page, makes the directory path for html pages if not made
  129. def savePage(page, url):
  130. cleanPage = cleanHTML(page)
  131. filePath = getFullPathName(url)
  132. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  133. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  134. return
  135. # Gets the full path of the page to be saved along with its appropriate file name
  136. #@param: raw url as crawler crawls through every site
  137. def getFullPathName(url):
  138. from MarketPlaces.Initialization.markets_mining import CURRENT_DATE
  139. fileName = getNameFromURL(url)
  140. if isDescriptionLink(url):
  141. fullPath = r'..\CityMarket\HTML_Pages\\' + CURRENT_DATE + r'\\Description\\' + fileName + '.html'
  142. else:
  143. fullPath = r'..\CityMarket\HTML_Pages\\' + CURRENT_DATE + r'\\Listing\\' + fileName + '.html'
  144. return fullPath
  145. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  146. #@param: raw url as crawler crawls through every site
  147. def getNameFromURL(url):
  148. global counter
  149. name = ''.join(e for e in url if e.isalnum())
  150. if (name == ''):
  151. name = str(counter)
  152. counter = counter + 1
  153. return name
  154. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  155. #in this example, there are a couple of categories some threads fall under such as
  156. # Guides and Tutorials, Digital Products, and Software and Malware
  157. #as you can see they are categories of products
  158. def getInterestedLinks():
  159. links = []
  160. # Hiring hacker
  161. links.append('http://wsptlnuoo3johqzcdlwuj5zcwfh2dwmswz6hahqctuxttvxpanypmwad.onion/?sub_id=3')
  162. # virus and malware
  163. links.append('http://wsptlnuoo3johqzcdlwuj5zcwfh2dwmswz6hahqctuxttvxpanypmwad.onion/?sub_id=15')
  164. # ddos
  165. links.append('http://wsptlnuoo3johqzcdlwuj5zcwfh2dwmswz6hahqctuxttvxpanypmwad.onion/?sub_id=16')
  166. # software
  167. links.append('http://wsptlnuoo3johqzcdlwuj5zcwfh2dwmswz6hahqctuxttvxpanypmwad.onion/?sub_id=17')
  168. # botnets
  169. links.append('http://wsptlnuoo3johqzcdlwuj5zcwfh2dwmswz6hahqctuxttvxpanypmwad.onion/?sub_id=18')
  170. # hacking service
  171. links.append('http://wsptlnuoo3johqzcdlwuj5zcwfh2dwmswz6hahqctuxttvxpanypmwad.onion/?sub_id=31')
  172. return links
  173. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  174. #topic and description pages are crawled through here, where both types of pages are saved
  175. #@param: selenium driver
  176. def crawlForum(driver):
  177. print("Crawling the CityMarket market")
  178. linksToCrawl = getInterestedLinks()
  179. visited = set(linksToCrawl)
  180. initialTime = time.time()
  181. count = 0
  182. i = 0
  183. while i < len(linksToCrawl):
  184. link = linksToCrawl[i]
  185. print('Crawling :', link)
  186. try:
  187. try:
  188. driver.get(link)
  189. except:
  190. driver.refresh()
  191. html = driver.page_source
  192. savePage(html, link)
  193. has_next_page = True
  194. while has_next_page:
  195. list = productPages(html)
  196. for item in list:
  197. itemURL = urlparse.urljoin(baseURL, str(item))
  198. try:
  199. driver.get(itemURL)
  200. except:
  201. driver.refresh()
  202. savePage(driver.page_source, item)
  203. driver.back()
  204. # comment out
  205. break
  206. # comment out
  207. if count == 1:
  208. count = 0
  209. break
  210. try:
  211. link = driver.find_element(by=By.XPATH, value=
  212. '/html/body/div[1]/div/div[2]/nav/ul/li[5]/a').get_attribute('href')
  213. if link == "":
  214. raise NoSuchElementException
  215. try:
  216. driver.get(link)
  217. except:
  218. driver.refresh()
  219. html = driver.page_source
  220. savePage(html, link)
  221. count += 1
  222. except NoSuchElementException:
  223. has_next_page = False
  224. except Exception as e:
  225. print(link, e)
  226. i += 1
  227. # finalTime = time.time()
  228. # print finalTime - initialTime
  229. input("Crawling CityMarket forum done sucessfully. Press ENTER to continue\n")
  230. # Returns 'True' if the link is a description link
  231. #@param: url of any url crawled
  232. #return: true if is a description page, false if not
  233. def isDescriptionLink(url):
  234. if 'single_product' in url:
  235. return True
  236. return False
  237. # Returns True if the link is a listingPage link
  238. #@param: url of any url crawled
  239. #return: true if is a Listing page, false if not
  240. def isListingLink(url):
  241. if 'sub_id' in url:
  242. return True
  243. return False
  244. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  245. #@param: link from interested link list ie. getInterestingLinks()
  246. #return: list of description links that should be crawled through
  247. def productPages(html):
  248. soup = BeautifulSoup(html, "html.parser")
  249. return city_links_parser(soup)
  250. # Drop links that "signout"
  251. # def isSignOut(url):
  252. # #absURL = urlparse.urljoin(url.base_url, url.url)
  253. # if 'signout' in url.lower() or 'logout' in url.lower():
  254. # return True
  255. #
  256. # return False
  257. def crawler():
  258. startCrawling()
  259. # print("Crawling and Parsing BestCardingWorld .... DONE!")