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. counter = 1
  24. baseURL = 'http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/'
  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. # wait for listing page show up (This Xpath may need to change based on different seed url)
  51. WebDriverWait(driver, 50).until(EC.visibility_of_element_located(
  52. (By.XPATH, '/html/body/div[2]/div[2]/div/div[2]/div[4]/div/ul/li[14]/a')))
  53. # Returns the name of the website
  54. def getForumName():
  55. name = 'HiddenAnswers'
  56. return name
  57. # Return the link of the website
  58. def getFixedURL():
  59. url = 'http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/'
  60. return url
  61. # Closes Tor Browser
  62. def closetor(driver):
  63. # global pid
  64. # os.system("taskkill /pid " + str(pro.pid))
  65. # os.system("taskkill /t /f /im tor.exe")
  66. print('Closing Tor...')
  67. driver.close()
  68. time.sleep(3)
  69. return
  70. # Creates FireFox 'driver' and configure its 'Profile'
  71. # to use Tor proxy and socket
  72. def createFFDriver():
  73. from Forums.Initialization.forums_mining import config
  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. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  118. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + getForumName() + "/HTML_Pages")
  119. fileName = getNameFromURL(url)
  120. if isDescriptionLink(url):
  121. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  122. else:
  123. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  124. return fullPath
  125. # Creates the file name from passed URL
  126. def getNameFromURL(url):
  127. global counter
  128. name = ''.join(e for e in url if e.isalnum())
  129. if (name == ''):
  130. name = str(counter)
  131. counter = counter + 1
  132. return name
  133. def getInterestedLinks():
  134. links = []
  135. # Hacks
  136. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/hacking')
  137. return links
  138. def crawlForum(driver):
  139. print("Crawling the HiddenAnswers forum")
  140. linksToCrawl = getInterestedLinks()
  141. visited = set(linksToCrawl)
  142. initialTime = time.time()
  143. i = 0
  144. count = 0
  145. while i < len(linksToCrawl):
  146. link = linksToCrawl[i]
  147. print('Crawling :', link)
  148. try:
  149. try:
  150. driver.get(link)
  151. except:
  152. driver.refresh()
  153. html = driver.page_source
  154. savePage(html, link)
  155. has_next_page = True
  156. while has_next_page:
  157. list = topicPages(html)
  158. for item in list:
  159. itemURL = urlparse.urljoin(baseURL, str(item))
  160. try:
  161. driver.get(itemURL)
  162. except:
  163. driver.refresh()
  164. savePage(driver.page_source, item)
  165. driver.back()
  166. '''
  167. #variable to check if there is a next page for the topic
  168. has_next_topic_page = True
  169. counter = 1
  170. # check if there is a next page for the topics
  171. while has_next_topic_page:
  172. # try to access next page of th topic
  173. itemURL = urlparse.urljoin(baseURL, str(item))
  174. try:
  175. driver.get(itemURL)
  176. except:
  177. driver.refresh()
  178. savePage(driver.page_source, item)
  179. # if there is a next page then go and save....
  180. # next page in the topic?
  181. try:
  182. temp = driver.find_element(By.XPATH, '/html/body/div/div[2]/div/div[2]/div') # /html/body/div/div[2]/div/div[2]/div/
  183. item = temp.find_element(by=By.CLASS_NAME, value='pagination_next').get_attribute('href') #/html/body/div/div[2]/div/div[2]/div
  184. if item == "":
  185. raise NoSuchElementException
  186. has_next_topic_page = False
  187. else:
  188. counter += 1
  189. except NoSuchElementException:
  190. has_next_topic_page = False
  191. # end of loop
  192. for i in range(counter):
  193. driver.back()
  194. '''
  195. # comment out
  196. break
  197. # comment out
  198. if count == 1:
  199. count = 0
  200. break
  201. try:
  202. 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')
  203. if link == "":
  204. raise NoSuchElementException
  205. try:
  206. driver.get(link)
  207. except:
  208. driver.refresh()
  209. html = driver.page_source
  210. savePage(html, link)
  211. count += 1
  212. except NoSuchElementException:
  213. has_next_page = False
  214. except Exception as e:
  215. print(link, e)
  216. i += 1
  217. # finalTime = time.time()
  218. # print finalTime - initialTime
  219. input("Crawling HiddenAnswers forum done sucessfully. Press ENTER to continue\n")
  220. # Returns 'True' if the link is Topic link
  221. def isDescriptionLink(url):
  222. if 'index.php' in url and 'questions' not in url:
  223. return True
  224. return False
  225. # Returns True if the link is a listingPage link
  226. def isListingLink(url):
  227. if 'questions' in url:
  228. return True
  229. return False
  230. # calling the parser to define the links
  231. def topicPages(html):
  232. soup = BeautifulSoup(html, "html.parser")
  233. #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)
  234. return hiddenanswers_links_parser(soup)
  235. def crawler():
  236. startCrawling()
  237. # print("Crawling and Parsing Abyss .... DONE!")