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.

276 lines
8.5 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. i = 0
  142. while i < len(linksToCrawl):
  143. link = linksToCrawl[i]
  144. print('Crawling :', link)
  145. try:
  146. has_next_page = True
  147. count = 0
  148. while has_next_page:
  149. try:
  150. driver.get(link)
  151. except:
  152. driver.refresh()
  153. html = driver.page_source
  154. savePage(html, link)
  155. topics = topicPages(html)
  156. for topic in topics:
  157. has_next_topic_page = True
  158. counter = 1
  159. page = topic
  160. while has_next_topic_page:
  161. itemURL = urlparse.urljoin(baseURL, str(page))
  162. try:
  163. driver.get(itemURL)
  164. except:
  165. driver.refresh()
  166. savePage(driver.page_source, topic + f"page{counter}") # very important
  167. # comment out
  168. if counter == 2:
  169. break
  170. try:
  171. page = "" # no next page so far may have some later on
  172. if page == "":
  173. raise NoSuchElementException
  174. counter += 1
  175. except NoSuchElementException:
  176. has_next_topic_page = False
  177. for i in range(counter):
  178. driver.back()
  179. # comment out
  180. break
  181. # comment out
  182. if count == 1:
  183. break
  184. try:
  185. 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')
  186. if link == "":
  187. raise NoSuchElementException
  188. count += 1
  189. except NoSuchElementException:
  190. has_next_page = False
  191. except Exception as e:
  192. print(link, e)
  193. i += 1
  194. input("Crawling HiddenAnswers done successfully. Press ENTER to continue\n")
  195. # Returns 'True' if the link is Topic link
  196. def isDescriptionLink(url):
  197. if 'index.php' in url and 'questions' not in url:
  198. return True
  199. return False
  200. # Returns True if the link is a listingPage link
  201. def isListingLink(url):
  202. if 'questions' in url:
  203. return True
  204. return False
  205. # calling the parser to define the links
  206. def topicPages(html):
  207. soup = BeautifulSoup(html, "html.parser")
  208. #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)
  209. return hiddenanswers_links_parser(soup)
  210. def crawler():
  211. startCrawling()
  212. # print("Crawling and Parsing Abyss .... DONE!")