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.6 KiB

  1. __author__ = 'DarkWeb'
  2. '''
  3. Dread 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. import urllib.parse as urlparse
  14. import os, re, time
  15. from datetime import date
  16. import subprocess
  17. from bs4 import BeautifulSoup
  18. from Forums.Initialization.prepare_parser import new_parse
  19. from Forums.Dread.parser import dread_links_parser
  20. from Forums.Utilities.utilities import cleanHTML
  21. counter = 1
  22. baseURL = 'http://dreadytofatroptsdj6io7l3xptbet6onoyno2yv7jicoxknyazubrad.onion/'
  23. # Opens Tor Browser, crawls the website
  24. def startCrawling():
  25. forumName = getForumName()
  26. driver = getAccess()
  27. if driver != 'down':
  28. try:
  29. login(driver)
  30. crawlForum(driver)
  31. except Exception as e:
  32. print(driver.current_url, e)
  33. closeDriver(driver)
  34. new_parse(forumName, baseURL, False)
  35. # Login using premade account credentials and do login captcha manually
  36. def login(driver):
  37. '''
  38. # code for captcha, for now, it runs too slow so captcha expires
  39. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  40. (By.CSS_SELECTOR, ".image")))
  41. inputBoxes = driver.find_elements(by=By.TAG_NAME, value='input')
  42. for index, inputBox in enumerate(inputBoxes):
  43. driver.find_element(by=By.CSS_SELECTOR, value='.image').screenshot(r'..\Dread\captcha.png')
  44. im = Image.open(r'..\Dread\captcha.png')
  45. im.show()
  46. userIn = input("Enter character: ")
  47. inputBox.send_keys(userIn)
  48. im.close()
  49. if index != 5:
  50. inputBoxes[index+1].click()
  51. driver.find_element(by=By.XPATH, value="/html/body/div/div[2]/div/form/div/input").click()
  52. '''
  53. input("Press ENTER when CAPTCHA is completed\n")
  54. #entering username and password into input boxes
  55. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  56. (By.XPATH, "/html/body/div/div[2]")))
  57. # Returns the name of the website
  58. def getForumName():
  59. name = 'Dread'
  60. return name
  61. # Return the link of the website
  62. def getFixedURL():
  63. url = 'http://dreadytofatroptsdj6io7l3xptbet6onoyno2yv7jicoxknyazubrad.onion/'
  64. return url
  65. # Closes Tor Browser
  66. def closeDriver(driver):
  67. # global pid
  68. # os.system("taskkill /pid " + str(pro.pid))
  69. # os.system("taskkill /t /f /im tor.exe")
  70. print('Closing Tor...')
  71. driver.close()
  72. time.sleep(3)
  73. return
  74. # Creates FireFox 'driver' and configure its 'Profile'
  75. # to use Tor proxy and socket
  76. def createFFDriver():
  77. from Forums.Initialization.forums_mining import config
  78. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  79. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  80. ff_prof.set_preference("places.history.enabled", False)
  81. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  82. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  83. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  84. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  85. ff_prof.set_preference("signon.rememberSignons", False)
  86. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  87. # ff_prof.set_preference("network.dns.disablePrefetch", True)
  88. # ff_prof.set_preference("network.http.sendRefererHeader", 0)
  89. ff_prof.set_preference("permissions.default.image", 3)
  90. ff_prof.set_preference("browser.download.folderList", 2)
  91. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  92. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  93. ff_prof.set_preference('network.proxy.type', 1)
  94. ff_prof.set_preference("network.proxy.socks_version", 5)
  95. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  96. ff_prof.set_preference('network.proxy.socks_port', 9150)
  97. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  98. ff_prof.set_preference("javascript.enabled", True)
  99. ff_prof.set_preference("xpinstall.signatures.required", False);
  100. ff_prof.update_preferences()
  101. service = Service(config.get('TOR', 'geckodriver_path'))
  102. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  103. driver.maximize_window()
  104. return driver
  105. def getAccess():
  106. url = getFixedURL()
  107. driver = createFFDriver()
  108. try:
  109. driver.get(url)
  110. return driver
  111. except:
  112. driver.close()
  113. return 'down'
  114. # Saves the crawled html page
  115. def savePage(driver, page, url):
  116. cleanPage = cleanHTML(driver, page)
  117. filePath = getFullPathName(url)
  118. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  119. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  120. return
  121. # Gets the full path of the page to be saved along with its appropriate file name
  122. def getFullPathName(url):
  123. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  124. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + getForumName() + "/HTML_Pages")
  125. fileName = getNameFromURL(url)
  126. if isDescriptionLink(url):
  127. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  128. else:
  129. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  130. return fullPath
  131. # Creates the file name from passed URL
  132. def getNameFromURL(url):
  133. global counter
  134. name = ''.join(e for e in url if e.isalnum())
  135. if (name == ''):
  136. name = str(counter)
  137. counter = counter + 1
  138. return name
  139. def getInterestedLinks():
  140. links = []
  141. # # OpSec
  142. # links.append('http://dreadytofatroptsdj6io7l3xptbet6onoyno2yv7jicoxknyazubrad.onion/d/OpSec')
  143. # Hacking 180
  144. links.append('http://dreadytofatroptsdj6io7l3xptbet6onoyno2yv7jicoxknyazubrad.onion/d/hacking')
  145. # # Jobs4Crypto
  146. # links.append('http://dreadytofatroptsdj6io7l3xptbet6onoyno2yv7jicoxknyazubrad.onion/d/Jobs4Crypto')
  147. # # Hacktown
  148. # links.append('http://dreadytofatroptsdj6io7l3xptbet6onoyno2yv7jicoxknyazubrad.onion/d/HackTown')
  149. # # Malware
  150. # links.append('http://dreadytofatroptsdj6io7l3xptbet6onoyno2yv7jicoxknyazubrad.onion/d/malware')
  151. # # Programming
  152. # links.append('http://dreadytofatroptsdj6io7l3xptbet6onoyno2yv7jicoxknyazubrad.onion/d/programming')
  153. return links
  154. def crawlForum(driver):
  155. print("Crawling the Dread forum")
  156. linksToCrawl = getInterestedLinks()
  157. i = 0
  158. while i < len(linksToCrawl):
  159. link = linksToCrawl[i]
  160. print('Crawling :', link)
  161. try:
  162. has_next_page = True
  163. count = 0
  164. while has_next_page:
  165. try:
  166. driver.get(link)
  167. except:
  168. driver.refresh()
  169. html = driver.page_source
  170. savePage(driver, html, link)
  171. topics = topicPages(html)
  172. for topic in topics:
  173. has_next_topic_page = True
  174. counter = 1
  175. page = topic
  176. while has_next_topic_page:
  177. itemURL = urlparse.urljoin(baseURL, str(page))
  178. try:
  179. driver.get(itemURL)
  180. except:
  181. driver.refresh()
  182. savePage(driver, driver.page_source, topic + f"page{counter}")
  183. # comment out
  184. if counter == 2:
  185. break
  186. try:
  187. page = driver.find_element(By.LINK_TEXT, value='Next').get_attribute('href')
  188. if page == "":
  189. raise NoSuchElementException
  190. counter += 1
  191. except NoSuchElementException:
  192. has_next_topic_page = False
  193. for i in range(counter):
  194. driver.back()
  195. # comment out
  196. break
  197. # comment out
  198. if count == 1:
  199. break
  200. try:
  201. temp = driver.find_element(by=By.CLASS_NAME, value="pagination")
  202. link = temp.find_element(by=By.CLASS_NAME, value="next").get_attribute('href')
  203. if link == "":
  204. raise NoSuchElementException
  205. count += 1
  206. except NoSuchElementException:
  207. has_next_page = False
  208. except Exception as e:
  209. print(link, e)
  210. i += 1
  211. input("Crawling Dread forum done sucessfully. Press ENTER to continue\n")
  212. # Returns 'True' if the link is Topic link
  213. def isDescriptionLink(url):
  214. if '/post/' in url:
  215. return True
  216. return False
  217. # Returns True if the link is a listingPage link
  218. def isListingLink(url):
  219. if '/d/' in url:
  220. return True
  221. return False
  222. # calling the parser to define the links
  223. def topicPages(html):
  224. soup = BeautifulSoup(html, "html.parser")
  225. #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)
  226. return dread_links_parser(soup)
  227. def crawler():
  228. startCrawling()
  229. # print("Crawling and Parsing BestCardingWorld .... DONE!")