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.

286 lines
9.0 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: webdriver.Firefox = 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, True)
  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. driver.maximize_window()
  99. return driver
  100. def getAccess():
  101. url = getFixedURL()
  102. driver = createFFDriver()
  103. try:
  104. driver.get(url)
  105. return driver
  106. except:
  107. driver.close()
  108. return 'down'
  109. # Saves the crawled html page
  110. def savePage(driver, page, url):
  111. cleanPage = cleanHTML(driver, page)
  112. filePath = getFullPathName(url)
  113. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  114. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  115. return
  116. # Gets the full path of the page to be saved along with its appropriate file name
  117. def getFullPathName(url):
  118. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  119. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + getForumName() + "/HTML_Pages")
  120. fileName = getNameFromURL(url)
  121. if isDescriptionLink(url):
  122. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  123. else:
  124. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  125. return fullPath
  126. # Creates the file name from passed URL
  127. def getNameFromURL(url):
  128. global counter
  129. name = ''.join(e for e in url if e.isalnum())
  130. if (name == ''):
  131. name = str(counter)
  132. counter = counter + 1
  133. return name
  134. def getInterestedLinks():
  135. links = []
  136. # Hacks
  137. # links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/hacking')
  138. # links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/darknet-and-tor')
  139. # links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/internet')
  140. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/links')
  141. return links
  142. def crawlForum(driver: webdriver.Firefox):
  143. print("Crawling the HiddenAnswers forum")
  144. linksToCrawl = getInterestedLinks()
  145. i = 0
  146. while i < len(linksToCrawl):
  147. link = linksToCrawl[i]
  148. print('Crawling :', link)
  149. try:
  150. has_next_page = True
  151. count = 0
  152. while has_next_page:
  153. try:
  154. driver.get(link)
  155. except:
  156. driver.refresh()
  157. html = driver.page_source
  158. savePage(driver, html, link)
  159. topics = topicPages(html)
  160. for topic in topics:
  161. has_next_topic_page = True
  162. counter = 1
  163. page = topic
  164. while has_next_topic_page:
  165. itemURL = urlparse.urljoin(baseURL, str(page))
  166. try:
  167. driver.get(itemURL)
  168. except:
  169. driver.refresh()
  170. savePage(driver, driver.page_source, topic + f"page{counter}") # very important
  171. # comment out
  172. if counter == 2:
  173. break
  174. try:
  175. page = "" # no next page so far may have some later on
  176. if page == "":
  177. raise NoSuchElementException
  178. counter += 1
  179. except NoSuchElementException:
  180. has_next_topic_page = False
  181. for i in range(counter):
  182. driver.back()
  183. # comment out
  184. # break
  185. # comment out
  186. if count == 1:
  187. break
  188. try:
  189. link = driver.find_element(by=By.CLASS_NAME, value='qa-page-next').get_attribute('href')
  190. if link == "":
  191. raise NoSuchElementException
  192. count += 1
  193. except NoSuchElementException:
  194. has_next_page = False
  195. except Exception as e:
  196. print(link, e)
  197. i += 1
  198. print("Crawling the HiddenAnswers forum done.")
  199. # Returns 'True' if the link is Topic link
  200. def isDescriptionLink(url):
  201. if 'index.php' in url and 'questions' not in url:
  202. return True
  203. return False
  204. # Returns True if the link is a listingPage link
  205. def isListingLink(url):
  206. if 'questions' in url:
  207. return True
  208. return False
  209. # calling the parser to define the links
  210. def topicPages(html):
  211. soup = BeautifulSoup(html, "html.parser")
  212. #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)
  213. return hiddenanswers_links_parser(soup)
  214. def crawler():
  215. startCrawling()
  216. # print("Crawling and Parsing Abyss .... DONE!")