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.

316 lines
10 KiB

1 year ago
  1. __author__ = 'Helium'
  2. '''
  3. Altenens 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.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. from datetime import date
  17. import configparser
  18. import subprocess
  19. from bs4 import BeautifulSoup
  20. from Forums.Initialization.prepare_parser import new_parse
  21. from Forums.Altenens.parser import altenens_links_parser
  22. from Forums.Utilities.utilities import cleanHTML
  23. counter = 1
  24. baseURL = 'https://altenens.is/'
  25. # Opens Tor Browser, crawls the website
  26. def startCrawling():
  27. opentor()
  28. forumName = getForumName()
  29. driver = getAccess()
  30. if driver != 'down':
  31. try:
  32. # login(driver)
  33. crawlForum(driver)
  34. except Exception as e:
  35. print(driver.current_url, e)
  36. closetor(driver)
  37. new_parse(forumName, baseURL, False)
  38. # Opens Tor Browser
  39. def opentor():
  40. from Forums.Initialization.forums_mining import config
  41. global pid
  42. print("Connecting Tor...")
  43. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  44. pid = pro.pid
  45. time.sleep(7.5)
  46. input('Tor Connected. Press ENTER to continue\n')
  47. return
  48. # Login using premade account credentials and do login captcha manually
  49. def login(driver):
  50. #click login button
  51. login = driver.find_element(by=By.XPATH, value='//*[@id="top"]/div[1]/div/div/div/div[1]/a[1]')
  52. login.click()
  53. #entering username and password into input boxes
  54. usernameBox = driver.find_element(by=By.XPATH, value='//*[@id="_xfUid-1-1688066635"]')
  55. #Username here
  56. usernameBox.send_keys('mylittlepony45')#sends string to the username box
  57. passwordBox = driver.find_element(by=By.XPATH, value='//*[@id="_xfUid-2-1688066635"]')
  58. #Password here
  59. passwordBox.send_keys('johnnyTest@18')# sends string to passwordBox
  60. input("Press ENTER when CAPTCHA is completed\n")
  61. # wait for listing page show up (This Xpath may need to change based on different seed url)
  62. # wait for 50 sec until id = tab_content is found, then cont
  63. WebDriverWait(driver, 50).until(EC.visibility_of_element_located(
  64. (By.XPATH, '///html/body/div[1]/div[4]/div/div/div[3]/div/div/div[4]/div/div/div[1]/div/div[1]/div[2]/ol/li[1]')))
  65. # Returns the name of the website
  66. def getForumName():
  67. name = 'Altenens'
  68. return name
  69. # Return the link of the website
  70. def getFixedURL():
  71. url = 'https://altenens.is/'
  72. return url
  73. # Closes Tor Browser
  74. def closetor(driver):
  75. # global pid
  76. # os.system("taskkill /pid " + str(pro.pid))
  77. # os.system("taskkill /t /f /im tor.exe")
  78. print('Closing Tor...')
  79. driver.close() #close tab
  80. time.sleep(3)
  81. return
  82. # Creates FireFox 'driver' and configure its 'Profile'
  83. # to use Tor proxy and socket
  84. def createFFDriver():
  85. from Forums.Initialization.forums_mining import config
  86. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  87. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  88. ff_prof.set_preference("places.history.enabled", False)
  89. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  90. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  91. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  92. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  93. ff_prof.set_preference("signon.rememberSignons", False)
  94. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  95. ff_prof.set_preference("network.dns.disablePrefetch", True)
  96. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  97. ff_prof.set_preference("permissions.default.image", 3)
  98. ff_prof.set_preference("browser.download.folderList", 2)
  99. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  100. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  101. ff_prof.set_preference('network.proxy.type', 1)
  102. ff_prof.set_preference("network.proxy.socks_version", 5)
  103. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  104. ff_prof.set_preference('network.proxy.socks_port', 9150)
  105. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  106. ff_prof.set_preference("javascript.enabled", True)
  107. ff_prof.update_preferences()
  108. service = Service(config.get('TOR', 'geckodriver_path'))
  109. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  110. return driver
  111. def getAccess():
  112. url = getFixedURL()
  113. driver = createFFDriver()
  114. try:
  115. driver.get(url)# open url in browser
  116. return driver
  117. except:
  118. driver.close()# close tab
  119. return 'down'
  120. # Saves the crawled html page
  121. def savePage(page, url):
  122. cleanPage = cleanHTML(page)
  123. filePath = getFullPathName(url)
  124. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  125. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  126. return
  127. # Gets the full path of the page to be saved along with its appropriate file name
  128. def getFullPathName(url):
  129. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  130. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + getForumName() + "/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
  138. def getNameFromURL(url):
  139. global counter
  140. name = ''.join(e for e in url if e.isalnum())
  141. if (name == ''):
  142. name = str(counter)
  143. counter = counter + 1
  144. return name
  145. def getInterestedLinks():
  146. links = []
  147. # # Hacking Tools
  148. links.append('https://altenens.is/forums/hacking-tools.469165/')
  149. # # hash cracking
  150. # links.append('https://altenens.is/forums/hash-cracking.469167/')
  151. # # phishing and spamming
  152. # links.append('https://altenens.is/forums/phishing-and-spamming.469223/')
  153. # # pentesting
  154. # links.append('https://altenens.is/forums/pentesting.469169/')
  155. # # cracking tools
  156. # links.append('https://altenens.is/forums/cracking-tools.469204/')
  157. # # Cracking Tools
  158. # links.append('https://altenens.is/forums/cracking-tutorials-other-methods.469205/')
  159. return links
  160. def crawlForum(driver):
  161. print("Crawling the Altenens forum")
  162. linksToCrawl = getInterestedLinks()
  163. visited = set(linksToCrawl)
  164. initialTime = time.time()
  165. i = 0
  166. count = 0
  167. while i < len(linksToCrawl):
  168. link = linksToCrawl[i]
  169. print('Crawling :', link)
  170. try:
  171. try:
  172. driver.get(link)# open
  173. except:
  174. driver.refresh()
  175. html = driver.page_source
  176. savePage(html, link)
  177. has_next_page = True
  178. #loop through the topics
  179. while has_next_page:
  180. list = topicPages(html)# for multiple pages
  181. for item in list:
  182. #variable to check if there is a next page for the topic
  183. has_next_topic_page = True
  184. counter = 1
  185. # check if there is a next page for the topics
  186. while has_next_topic_page:
  187. # try to access next page of th topic
  188. itemURL = urlparse.urljoin(baseURL, str(item))
  189. try:
  190. driver.get(itemURL)
  191. except:
  192. driver.refresh()
  193. savePage(driver.page_source, item)
  194. # if there is a next page then go and save....
  195. # next page in the topic?
  196. try:
  197. item = driver.find_element(By.XPATH, '/html/body/div[1]/div[4]/div/div/div[3]/div/div/div[1]/div[1]/div[1]/nav/div[1]/a').get_attribute('href')
  198. if item == "":
  199. raise NoSuchElementException
  200. has_next_topic_page = False
  201. else:
  202. counter += 1
  203. except NoSuchElementException:
  204. has_next_topic_page = False
  205. #end of loop
  206. for i in range(counter):
  207. driver.back()
  208. # comment out
  209. break
  210. # comment out
  211. if count == 1:
  212. count = 0
  213. break
  214. try:# change depending on web page, #next page
  215. link = driver.find_element(by=By.XPATH, value = '/html/body/div[1]/div[4]/div/div/div[3]/div/div/div/div[1]/div[1]/nav/div[1]/a').get_attribute('href')
  216. if link == "":
  217. raise NoSuchElementException
  218. try:
  219. driver.get(link)
  220. except:
  221. driver.refresh()
  222. html = driver.page_source
  223. savePage(html, link)
  224. count += 1
  225. except NoSuchElementException:
  226. has_next_page = False
  227. except Exception as e:
  228. print(link, e)
  229. i += 1
  230. # finalTime = time.time()
  231. # print finalTime - initialTime
  232. input("Crawling Altenens forum done successfully. Press ENTER to continue\n")
  233. # Returns 'True' if the link is Topic link, may need to change for every website
  234. def isDescriptionLink(url):
  235. if 'threads' in url:
  236. return True
  237. return False
  238. # Returns True if the link is a listingPage link, may need to change for every website
  239. def isListingLink(url):
  240. if 'forums' in url:
  241. return True
  242. return False
  243. # calling the parser to define the links
  244. def topicPages(html):
  245. soup = BeautifulSoup(html, "html.parser")
  246. #print(soup.find('div', id="container").find('div', id="content").find('table', {"class": "tborder clear"}).find('tbody').find('tr',{"class": "inline_row"}).find('strong').text)
  247. return altenens_links_parser(soup)
  248. def crawler():
  249. startCrawling()
  250. # print("Crawling and Parsing BestCardingWorld .... DONE!")