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

  1. __author__ = 'Helium'
  2. '''
  3. HiddenAnswers 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.HiddenAnswers.parser import hiddenanswers_links_parser
  22. from Forums.Utilities.utilities import cleanHTML
  23. config = configparser.ConfigParser()
  24. config.read('../../setup.ini')
  25. counter = 1
  26. baseURL = 'http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/'
  27. # Opens Tor Browser, crawls the website
  28. def startCrawling():
  29. opentor()
  30. # forumName = getForumName()
  31. driver = getAccess()
  32. if driver != 'down':
  33. try:
  34. login(driver)
  35. crawlForum(driver)
  36. except Exception as e:
  37. print(driver.current_url, e)
  38. closetor(driver)
  39. # new_parse(forumName, baseURL, False)
  40. # Opens Tor Browser
  41. def opentor():
  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. # wait for listing page show up (This Xpath may need to change based on different seed url)
  52. WebDriverWait(driver, 50).until(EC.visibility_of_element_located(
  53. (By.XPATH, '/html/body/div[2]/div[2]/div/div[2]/div[4]/div/ul/li[14]/a')))
  54. # Returns the name of the website
  55. def getForumName():
  56. name = 'HiddenAnswers'
  57. return name
  58. # Return the link of the website
  59. def getFixedURL():
  60. url = 'http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/'
  61. return url
  62. # Closes Tor Browser
  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", 3)
  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", True)
  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. def getAccess():
  100. url = getFixedURL()
  101. driver = createFFDriver()
  102. try:
  103. driver.get(url)
  104. return driver
  105. except:
  106. driver.close()
  107. return 'down'
  108. # Saves the crawled html page
  109. def savePage(page, url):
  110. cleanPage = cleanHTML(page)
  111. filePath = getFullPathName(url)
  112. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  113. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  114. return
  115. # Gets the full path of the page to be saved along with its appropriate file name
  116. def getFullPathName(url):
  117. fileName = getNameFromURL(url)
  118. if isDescriptionLink(url):
  119. #..\CryptBB\HTML_Pages\\
  120. fullPath = r'..\HiddenAnswers\HTML_Pages\\' + str(
  121. "%02d" % date.today().month) + str("%02d" % date.today().day) + str(
  122. "%04d" % date.today().year) + r'\\' + r'Description\\' + fileName + '.html'
  123. else:
  124. fullPath = r'..\HiddenAnswers\HTML_Pages\\' + str(
  125. "%02d" % date.today().month) + str("%02d" % date.today().day) + str(
  126. "%04d" % date.today().year) + r'\\' + r'Listing\\' + fileName + '.html'
  127. return fullPath
  128. # Creates the file name from passed URL
  129. def getNameFromURL(url):
  130. global counter
  131. name = ''.join(e for e in url if e.isalnum())
  132. if (name == ''):
  133. name = str(counter)
  134. counter = counter + 1
  135. return name
  136. def getInterestedLinks():
  137. links = []
  138. # Hacks
  139. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/hacking')
  140. return links
  141. def crawlForum(driver):
  142. print("Crawling the HiddenAnswers forum")
  143. linksToCrawl = getInterestedLinks()
  144. visited = set(linksToCrawl)
  145. initialTime = time.time()
  146. i = 0
  147. count = 0
  148. while i < len(linksToCrawl):
  149. link = linksToCrawl[i]
  150. print('Crawling :', link)
  151. try:
  152. try:
  153. driver.get(link)
  154. except:
  155. driver.refresh()
  156. html = driver.page_source
  157. savePage(html, link)
  158. has_next_page = True
  159. while has_next_page:
  160. list = topicPages(html)
  161. for item in list:
  162. itemURL = urlparse.urljoin(baseURL, str(item))
  163. try:
  164. driver.get(itemURL)
  165. except:
  166. driver.refresh()
  167. savePage(driver.page_source, item)
  168. driver.back()
  169. '''
  170. #variable to check if there is a next page for the topic
  171. has_next_topic_page = True
  172. counter = 1
  173. # check if there is a next page for the topics
  174. while has_next_topic_page:
  175. # try to access next page of th topic
  176. itemURL = urlparse.urljoin(baseURL, str(item))
  177. try:
  178. driver.get(itemURL)
  179. except:
  180. driver.refresh()
  181. savePage(driver.page_source, item)
  182. # if there is a next page then go and save....
  183. # next page in the topic?
  184. try:
  185. temp = driver.find_element(By.XPATH, '/html/body/div/div[2]/div/div[2]/div') # /html/body/div/div[2]/div/div[2]/div/
  186. item = temp.find_element(by=By.CLASS_NAME, value='pagination_next').get_attribute('href') #/html/body/div/div[2]/div/div[2]/div
  187. if item == "":
  188. raise NoSuchElementException
  189. has_next_topic_page = False
  190. else:
  191. counter += 1
  192. except NoSuchElementException:
  193. has_next_topic_page = False
  194. # end of loop
  195. for i in range(counter):
  196. driver.back()
  197. '''
  198. # comment out
  199. break
  200. # comment out
  201. if count == 1:
  202. count = 0
  203. break
  204. try:
  205. link = driver.find_element(by=By.XPATH, value = '/html/body/div[2]/div[2]/div/div[3]/div[3]/ul/li[7]/a').get_attribute('href')
  206. if link == "":
  207. raise NoSuchElementException
  208. try:
  209. driver.get(link)
  210. except:
  211. driver.refresh()
  212. html = driver.page_source
  213. savePage(html, link)
  214. count += 1
  215. except NoSuchElementException:
  216. has_next_page = False
  217. except Exception as e:
  218. print(link, e)
  219. i += 1
  220. # finalTime = time.time()
  221. # print finalTime - initialTime
  222. input("Crawling HiddenAnswers forum done sucessfully. Press ENTER to continue\n")
  223. # Returns 'True' if the link is Topic link
  224. def isDescriptionLink(url):
  225. if 'index.php' in url and 'questions' not in url:
  226. return True
  227. return False
  228. # Returns True if the link is a listingPage link
  229. def isListingLink(url):
  230. if 'questions' in url:
  231. return True
  232. return False
  233. # calling the parser to define the links
  234. def topicPages(html):
  235. soup = BeautifulSoup(html, "html.parser")
  236. #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)
  237. return hiddenanswers_links_parser(soup)
  238. def crawler():
  239. startCrawling()
  240. # print("Crawling and Parsing Abyss .... DONE!")