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.

301 lines
9.8 KiB

1 year ago
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. #
  31. # if driver != 'down':
  32. # try:
  33. # login(driver)
  34. # crawlForum(driver)
  35. # except Exception as e:
  36. # print(driver.current_url, e)
  37. # closetor(driver)
  38. new_parse(forumName, baseURL, True)
  39. # Opens Tor Browser
  40. def opentor():
  41. from Forums.Initialization.forums_mining import config
  42. global pid
  43. print("Connecting Tor...")
  44. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  45. pid = pro.pid
  46. time.sleep(7.5)
  47. input('Tor Connected. Press ENTER to continue\n')
  48. return
  49. # Login using premade account credentials and do login captcha manually
  50. def login(driver):
  51. #click login button
  52. login_link = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[1]/div/div/div/div[1]/a[1]').get_attribute('href')
  53. driver.get(login_link) # open tab with url
  54. #entering username and password into input boxes
  55. usernameBox = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[4]/div/div/div[3]/div/div/div/form/div[1]/div/dl[1]/dd/input')
  56. #Username here
  57. usernameBox.send_keys('mylittlepony45')#sends string to the username box
  58. passwordBox = driver.find_element(by=By.XPATH, value='/html/body/div[1]/div[4]/div/div/div[3]/div/div/div/form/div[1]/div/dl[2]/dd/div/div/input')
  59. #Password here
  60. passwordBox.send_keys('johnnyTest@18')# sends string to passwordBox
  61. input("Press ENTER when CAPTCHA is completed\n")
  62. # wait for listing page show up (This Xpath may need to change based on different seed url)
  63. # wait for 50 sec until id = tab_content is found, then cont
  64. WebDriverWait(driver, 50).until(EC.visibility_of_element_located(
  65. (By.XPATH, '/html/body/div[1]/div[1]/div/div/div/div[1]/a[1]')))
  66. # Returns the name of the website
  67. def getForumName():
  68. name = 'Altenens'
  69. return name
  70. # Return the link of the website
  71. def getFixedURL():
  72. url = 'https://altenens.is/'
  73. return url
  74. # Closes Tor Browser
  75. def closetor(driver):
  76. # global pid
  77. # os.system("taskkill /pid " + str(pro.pid))
  78. # os.system("taskkill /t /f /im tor.exe")
  79. print('Closing Tor...')
  80. driver.close() #close tab
  81. time.sleep(3)
  82. return
  83. # Creates FireFox 'driver' and configure its 'Profile'
  84. # to use Tor proxy and socket
  85. def createFFDriver():
  86. from Forums.Initialization.forums_mining import config
  87. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  88. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  89. ff_prof.set_preference("places.history.enabled", False)
  90. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  91. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  92. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  93. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  94. ff_prof.set_preference("signon.rememberSignons", False)
  95. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  96. ff_prof.set_preference("network.dns.disablePrefetch", True)
  97. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  98. ff_prof.set_preference("permissions.default.image", 3)
  99. ff_prof.set_preference("browser.download.folderList", 2)
  100. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  101. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  102. ff_prof.set_preference('network.proxy.type', 1)
  103. ff_prof.set_preference("network.proxy.socks_version", 5)
  104. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  105. ff_prof.set_preference('network.proxy.socks_port', 9150)
  106. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  107. ff_prof.set_preference("javascript.enabled", True)
  108. ff_prof.update_preferences()
  109. service = Service(config.get('TOR', 'geckodriver_path'))
  110. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  111. return driver
  112. def getAccess():
  113. url = getFixedURL()
  114. driver = createFFDriver()
  115. try:
  116. driver.get(url)# open url in browser
  117. return driver
  118. except:
  119. driver.close()# close tab
  120. return 'down'
  121. # Saves the crawled html page
  122. def savePage(page, url):
  123. cleanPage = cleanHTML(page)
  124. filePath = getFullPathName(url)
  125. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  126. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  127. return
  128. # Gets the full path of the page to be saved along with its appropriate file name
  129. def getFullPathName(url):
  130. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  131. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + getForumName() + "/HTML_Pages")
  132. fileName = getNameFromURL(url)
  133. if isDescriptionLink(url):
  134. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  135. else:
  136. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  137. return fullPath
  138. # Creates the file name from passed URL
  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. def getInterestedLinks():
  147. links = []
  148. # # Hacking Tools
  149. links.append('https://altenens.is/forums/hacking-tools.469165/')
  150. # # hash cracking
  151. # links.append('https://altenens.is/forums/hash-cracking.469167/')
  152. # # phishing and spamming
  153. # links.append('https://altenens.is/forums/phishing-and-spamming.469223/')
  154. # # pentesting
  155. # links.append('https://altenens.is/forums/pentesting.469169/')
  156. # # cracking tools
  157. # links.append('https://altenens.is/forums/cracking-tools.469204/')
  158. # # Cracking Tools
  159. # links.append('https://altenens.is/forums/cracking-tutorials-other-methods.469205/')
  160. return links
  161. # newest version of crawling
  162. def crawlForum(driver):
  163. print("Crawling the Altenens forum")
  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(html, link)
  179. topics = topicPages(html)
  180. for topic in topics:
  181. has_next_topic_page = True
  182. counter = 1
  183. page = topic
  184. while has_next_topic_page:
  185. itemURL = urlparse.urljoin(baseURL, str(page))
  186. try:
  187. driver.get(itemURL)
  188. except:
  189. driver.refresh()
  190. savePage(driver.page_source, topic + f"page{counter}") # very important
  191. # comment out
  192. if counter == 2:
  193. break
  194. try:
  195. page = driver.find_element(By.LINK_TEXT, value='Next').get_attribute('href')
  196. if page == "":
  197. raise NoSuchElementException
  198. counter += 1
  199. except NoSuchElementException:
  200. has_next_topic_page = False
  201. for i in range(counter):
  202. driver.back()
  203. # comment out
  204. break
  205. # comment out
  206. if count == 1:
  207. break
  208. try:
  209. link = driver.find_element(by=By.LINK_TEXT, value='Next').get_attribute('href')
  210. if link == "":
  211. raise NoSuchElementException
  212. count += 1
  213. except NoSuchElementException:
  214. has_next_page = False
  215. except Exception as e:
  216. print(link, e)
  217. i += 1
  218. input("Crawling Altenens forum done successfully. Press ENTER to continue\n")
  219. # Returns 'True' if the link is Topic link, may need to change for every website
  220. def isDescriptionLink(url):
  221. if 'threads' in url:
  222. return True
  223. return False
  224. # Returns True if the link is a listingPage link, may need to change for every website
  225. def isListingLink(url):
  226. if 'forums' in url:
  227. return True
  228. return False
  229. # calling the parser to define the links
  230. def topicPages(html):
  231. soup = BeautifulSoup(html, "html.parser")
  232. #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)
  233. return altenens_links_parser(soup)
  234. def crawler():
  235. startCrawling()
  236. # print("Crawling and Parsing BestCardingWorld .... DONE!")