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
9.1 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. # hacking
  126. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/hacking')
  127. # darknet and tor
  128. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/darknet-and-tor')
  129. # internet
  130. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/internet')
  131. # links
  132. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/questions/links')
  133. # programming
  134. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/programming')
  135. # knowledge and information
  136. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/knowledge-and-information')
  137. # other
  138. links.append('http://7eoz4h2nvw4zlr7gvlbutinqqpm546f5egswax54az6lt2u7e3t6d7yd.onion/index.php/other')
  139. return links
  140. def crawlForum(driver: webdriver.Firefox):
  141. print("Crawling the HiddenAnswers forum")
  142. linksToCrawl = getInterestedLinks()
  143. i = 0
  144. while i < len(linksToCrawl):
  145. link = linksToCrawl[i]
  146. print('Crawling :', link)
  147. try:
  148. has_next_page = True
  149. count = 0
  150. while has_next_page:
  151. try:
  152. driver.get(link)
  153. except:
  154. driver.refresh()
  155. html = driver.page_source
  156. savePage(driver, html, link)
  157. topics = topicPages(html)
  158. for topic in topics:
  159. has_next_topic_page = True
  160. counter = 1
  161. page = topic
  162. while has_next_topic_page:
  163. itemURL = urlparse.urljoin(baseURL, str(page))
  164. try:
  165. driver.get(itemURL)
  166. except:
  167. driver.refresh()
  168. savePage(driver, driver.page_source, topic + f"page{counter}") # very important
  169. # # comment out
  170. # if counter == 2:
  171. # break
  172. try:
  173. page = driver.find_element(by=By.CLASS_NAME, value='qa-page-next').get_attribute('href')
  174. if page == "":
  175. raise NoSuchElementException
  176. counter += 1
  177. except NoSuchElementException:
  178. has_next_topic_page = False
  179. for j in range(counter):
  180. driver.back()
  181. # # comment out
  182. # break
  183. #
  184. # # comment out
  185. # if count == 1:
  186. # break
  187. try:
  188. link = driver.find_element(by=By.CLASS_NAME, value='qa-page-next').get_attribute('href')
  189. if link == "":
  190. raise NoSuchElementException
  191. count += 1
  192. except NoSuchElementException:
  193. has_next_page = False
  194. except Exception as e:
  195. print(link, e)
  196. i += 1
  197. print("Crawling the HiddenAnswers forum done.")
  198. # Returns 'True' if the link is Topic link
  199. def isDescriptionLink(url):
  200. if 'http' not in url:
  201. return True
  202. return False
  203. # Returns True if the link is a listingPage link
  204. def isListingLink(url):
  205. if 'http' in url:
  206. return True
  207. return False
  208. # calling the parser to define the links
  209. def topicPages(html):
  210. soup = BeautifulSoup(html, "html.parser")
  211. #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)
  212. return hiddenanswers_links_parser(soup)
  213. def crawler():
  214. startCrawling()
  215. # print("Crawling and Parsing Abyss .... DONE!")