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.

272 lines
8.6 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. forumName = getForumName()
  28. driver: webdriver.Firefox = getAccess()
  29. if driver != 'down':
  30. try:
  31. login(driver)
  32. crawlForum(driver)
  33. except Exception as e:
  34. print(driver.current_url, e)
  35. closeDriver(driver)
  36. new_parse(forumName, baseURL, True)
  37. # Login using premade account credentials and do login captcha manually
  38. def login(driver):
  39. # wait for listing page show up (This Xpath may need to change based on different seed url)
  40. WebDriverWait(driver, 50).until(EC.visibility_of_element_located(
  41. (By.XPATH, '/html/body/div[2]/div[2]/div/div[2]/div[4]/div/ul/li[14]/a')))
  42. # Returns the name of the website
  43. def getForumName():
  44. name = 'HiddenAnswers'
  45. return name
  46. # Return the link of the website
  47. def getFixedURL():
  48. url = 'http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/'
  49. return url
  50. # Closes Tor Browser
  51. def closeDriver(driver):
  52. # global pid
  53. # os.system("taskkill /pid " + str(pro.pid))
  54. # os.system("taskkill /t /f /im tor.exe")
  55. print('Closing Tor...')
  56. driver.close()
  57. time.sleep(3)
  58. return
  59. # Creates FireFox 'driver' and configure its 'Profile'
  60. # to use Tor proxy and socket
  61. def createFFDriver():
  62. from Forums.Initialization.forums_mining import config
  63. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  64. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  65. ff_prof.set_preference("places.history.enabled", False)
  66. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  67. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  68. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  69. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  70. ff_prof.set_preference("signon.rememberSignons", False)
  71. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  72. ff_prof.set_preference("network.dns.disablePrefetch", True)
  73. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  74. ff_prof.set_preference("permissions.default.image", 3)
  75. ff_prof.set_preference("browser.download.folderList", 2)
  76. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  77. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  78. ff_prof.set_preference('network.proxy.type', 1)
  79. ff_prof.set_preference("network.proxy.socks_version", 5)
  80. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  81. ff_prof.set_preference('network.proxy.socks_port', 9150)
  82. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  83. ff_prof.set_preference("javascript.enabled", True)
  84. ff_prof.update_preferences()
  85. service = Service(config.get('TOR', 'geckodriver_path'))
  86. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  87. driver.maximize_window()
  88. return driver
  89. def getAccess():
  90. url = getFixedURL()
  91. driver = createFFDriver()
  92. try:
  93. driver.get(url)
  94. return driver
  95. except:
  96. driver.close()
  97. return 'down'
  98. # Saves the crawled html page
  99. def savePage(driver, page, url):
  100. cleanPage = cleanHTML(driver, page)
  101. filePath = getFullPathName(url)
  102. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  103. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  104. return
  105. # Gets the full path of the page to be saved along with its appropriate file name
  106. def getFullPathName(url):
  107. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  108. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + getForumName() + "/HTML_Pages")
  109. fileName = getNameFromURL(url)
  110. if isDescriptionLink(url):
  111. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  112. else:
  113. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  114. return fullPath
  115. # Creates the file name from passed URL
  116. def getNameFromURL(url):
  117. global counter
  118. name = ''.join(e for e in url if e.isalnum())
  119. if (name == ''):
  120. name = str(counter)
  121. counter = counter + 1
  122. return name
  123. def getInterestedLinks():
  124. links = []
  125. # Hacks
  126. # links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/hacking')
  127. # links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/darknet-and-tor')
  128. # links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/internet')
  129. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/links')
  130. return links
  131. def crawlForum(driver: webdriver.Firefox):
  132. print("Crawling the HiddenAnswers forum")
  133. linksToCrawl = getInterestedLinks()
  134. i = 0
  135. while i < len(linksToCrawl):
  136. link = linksToCrawl[i]
  137. print('Crawling :', link)
  138. try:
  139. has_next_page = True
  140. count = 0
  141. while has_next_page:
  142. try:
  143. driver.get(link)
  144. except:
  145. driver.refresh()
  146. html = driver.page_source
  147. savePage(driver, html, link)
  148. topics = topicPages(html)
  149. for topic in topics:
  150. has_next_topic_page = True
  151. counter = 1
  152. page = topic
  153. while has_next_topic_page:
  154. itemURL = urlparse.urljoin(baseURL, str(page))
  155. try:
  156. driver.get(itemURL)
  157. except:
  158. driver.refresh()
  159. savePage(driver, driver.page_source, topic + f"page{counter}") # very important
  160. # comment out
  161. if counter == 2:
  162. break
  163. try:
  164. page = "" # no next page so far may have some later on
  165. if page == "":
  166. raise NoSuchElementException
  167. counter += 1
  168. except NoSuchElementException:
  169. has_next_topic_page = False
  170. for i in range(counter):
  171. driver.back()
  172. # comment out
  173. # break
  174. # comment out
  175. if count == 1:
  176. break
  177. try:
  178. link = driver.find_element(by=By.CLASS_NAME, value='qa-page-next').get_attribute('href')
  179. if link == "":
  180. raise NoSuchElementException
  181. count += 1
  182. except NoSuchElementException:
  183. has_next_page = False
  184. except Exception as e:
  185. print(link, e)
  186. i += 1
  187. print("Crawling the HiddenAnswers forum done.")
  188. # Returns 'True' if the link is Topic link
  189. def isDescriptionLink(url):
  190. if 'index.php' in url and 'questions' not in url:
  191. return True
  192. return False
  193. # Returns True if the link is a listingPage link
  194. def isListingLink(url):
  195. if 'questions' in url:
  196. return True
  197. return False
  198. # calling the parser to define the links
  199. def topicPages(html):
  200. soup = BeautifulSoup(html, "html.parser")
  201. #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)
  202. return hiddenanswers_links_parser(soup)
  203. def crawler():
  204. startCrawling()
  205. # print("Crawling and Parsing Abyss .... DONE!")