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.

303 lines
9.6 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'DarkWeb'
  2. '''
  3. Libre Forum 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. import subprocess
  17. from bs4 import BeautifulSoup
  18. from Forums.Initialization.prepare_parser import new_parse
  19. from Forums.Libre.parser import libre_links_parser
  20. from Forums.Utilities.utilities import cleanHTML
  21. counter = 1
  22. baseURL = 'http://libreeunomyly6ot7kspglmbd5cvlkogib6rozy43r2glatc6rmwauqd.onion/'
  23. # Opens Tor Browser, crawls the website
  24. def startCrawling():
  25. # opentor()
  26. forumName = getForumName()
  27. # driver = getAccess()
  28. # if driver != 'down':
  29. # try:
  30. # login(driver)
  31. # crawlForum(driver)
  32. # except Exception as e:
  33. # print(driver.current_url, e)
  34. # closetor(driver)
  35. new_parse(forumName, baseURL, False)
  36. # Opens Tor Browser
  37. def opentor():
  38. from Forums.Initialization.forums_mining import config
  39. global pid
  40. print("Connecting Tor...")
  41. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  42. pid = pro.pid
  43. time.sleep(7.5)
  44. input('Tor Connected. Press ENTER to continue\n')
  45. return
  46. # Login using premade account credentials and do login captcha manually
  47. def login(driver):
  48. input('Press enter when CAPTCHA is completed, and you\'re at the login page')
  49. #entering username and password into input boxes
  50. usernameBox = driver.find_element(by=By.NAME, value='username')
  51. #Username here
  52. usernameBox.send_keys('ct1234')#sends string to the username box
  53. passwordBox = driver.find_element(by=By.NAME, value='password')
  54. #Password here
  55. passwordBox.send_keys('r5o0wqmw')# sends string to passwordBox
  56. input("Press the login button and solve the CAPTCHA then press enter\n")
  57. # input('input')
  58. # wait for listing page show up (This Xpath may need to change based on different seed url)
  59. # wait for 50 sec until id = tab_content is found, then cont
  60. WebDriverWait(driver, 50).until(EC.visibility_of_element_located(
  61. (By.TAG_NAME, 'nav')))
  62. # click link to correct forum board
  63. login_link = driver.find_element(by=By.XPATH, value='/html/body/nav/div[1]/a[3]').get_attribute('href')
  64. driver.get(login_link) # open tab with url
  65. # wait for listing page show up (This Xpath may need to change based on different seed url)
  66. # wait for 50 sec until id = tab_content is found, then cont
  67. WebDriverWait(driver, 50).until(EC.visibility_of_element_located(
  68. (By.XPATH, '/html/body/div/div/div[3]/div[5]')))
  69. # Returns the name of the website
  70. def getForumName() -> str:
  71. name = 'Libre'
  72. return name
  73. # Return the link of the website
  74. def getFixedURL():
  75. url = 'http://libreeunomyly6ot7kspglmbd5cvlkogib6rozy43r2glatc6rmwauqd.onion/'
  76. return url
  77. # Closes Tor Browser
  78. def closetor(driver):
  79. # global pid
  80. # os.system("taskkill /pid " + str(pro.pid))
  81. # os.system("taskkill /t /f /im tor.exe")
  82. print('Closing Tor...')
  83. driver.close() #close tab
  84. time.sleep(3)
  85. return
  86. # Creates FireFox 'driver' and configure its 'Profile'
  87. # to use Tor proxy and socket
  88. def createFFDriver():
  89. from Forums.Initialization.forums_mining import config
  90. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  91. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  92. ff_prof.set_preference("places.history.enabled", False)
  93. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  94. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  95. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  96. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  97. ff_prof.set_preference("signon.rememberSignons", False)
  98. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  99. ff_prof.set_preference("network.dns.disablePrefetch", True)
  100. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  101. ff_prof.set_preference("permissions.default.image", 3)
  102. ff_prof.set_preference("browser.download.folderList", 2)
  103. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  104. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  105. ff_prof.set_preference('network.proxy.type', 1)
  106. ff_prof.set_preference("network.proxy.socks_version", 5)
  107. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  108. ff_prof.set_preference('network.proxy.socks_port', 9150)
  109. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  110. ff_prof.set_preference("javascript.enabled", True)
  111. ff_prof.update_preferences()
  112. service = Service(config.get('TOR', 'geckodriver_path'))
  113. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  114. return driver
  115. def getAccess():
  116. url = getFixedURL()
  117. driver = createFFDriver()
  118. try:
  119. driver.get(url)
  120. return driver
  121. except:
  122. driver.close()
  123. return 'down'
  124. # Saves the crawled html page
  125. def savePage(page, url):
  126. cleanPage = cleanHTML(page)
  127. filePath = getFullPathName(url)
  128. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  129. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  130. return
  131. # Gets the full path of the page to be saved along with its appropriate file name
  132. def getFullPathName(url):
  133. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  134. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + getForumName() + "/HTML_Pages")
  135. fileName = getNameFromURL(url)
  136. if isDescriptionLink(url):
  137. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  138. else:
  139. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  140. return fullPath
  141. # Creates the file name from passed URL
  142. def getNameFromURL(url):
  143. global counter
  144. name = ''.join(e for e in url if e.isalnum())
  145. if name == '':
  146. name = str(counter)
  147. counter = counter + 1
  148. return name
  149. def getInterestedLinks():
  150. links = []
  151. # # cyber security
  152. links.append('http://libreeunomyly6ot7kspglmbd5cvlkogib6rozy43r2glatc6rmwauqd.onion/c/CyberSecurity')
  153. # # services
  154. # links.append('http://libreeunomyly6ot7kspglmbd5cvlkogib6rozy43r2glatc6rmwauqd.onion/c/Services')
  155. # # programming
  156. # links.append('http://libreeunomyly6ot7kspglmbd5cvlkogib6rozy43r2glatc6rmwauqd.onion/c/Programming')
  157. return links
  158. def crawlForum(driver):
  159. print("Crawling the Libre forum")
  160. linksToCrawl = getInterestedLinks()
  161. i = 0
  162. while i < len(linksToCrawl):
  163. link = linksToCrawl[i]
  164. print('Crawling :', link)
  165. try:
  166. has_next_page = True
  167. count = 0
  168. while has_next_page:
  169. try:
  170. driver.get(link)
  171. except:
  172. driver.refresh()
  173. html = driver.page_source
  174. savePage(html, link)
  175. topics = topicPages(html)
  176. for topic in topics:
  177. has_next_topic_page = True
  178. counter = 1
  179. page = topic
  180. while has_next_topic_page:
  181. itemURL = urlparse.urljoin(baseURL, str(page))
  182. try:
  183. driver.get(itemURL)
  184. except:
  185. driver.refresh()
  186. savePage(driver.page_source, topic + f"page{counter}") # very important
  187. # comment out
  188. if counter == 2:
  189. break
  190. try:
  191. page = "" # no next page so far may have some later on
  192. if page == "":
  193. raise NoSuchElementException
  194. counter += 1
  195. except NoSuchElementException:
  196. has_next_topic_page = False
  197. for i in range(counter):
  198. driver.back()
  199. # comment out
  200. break
  201. # comment out
  202. if count == 1:
  203. break
  204. try:
  205. link = driver.find_element(by=By.LINK_TEXT, value='>').get_attribute('href')
  206. if link == "":
  207. raise NoSuchElementException
  208. count += 1
  209. except NoSuchElementException:
  210. has_next_page = False
  211. except Exception as e:
  212. print(link, e)
  213. i += 1
  214. input("Crawling Libre done successfully. Press ENTER to continue\n")
  215. # Returns 'True' if the link is Topic link, may need to change for every website
  216. def isDescriptionLink(url):
  217. if '/p/' in url:
  218. return True
  219. return False
  220. # Returns True if the link is a listingPage link, may need to change for every website
  221. def isListingLink(url):
  222. if '/c/' in url:
  223. return True
  224. return False
  225. # calling the parser to define the links
  226. def topicPages(html):
  227. soup = BeautifulSoup(html, "html.parser")
  228. return libre_links_parser(soup)
  229. def crawler():
  230. startCrawling()
  231. # print("Crawling and Parsing BestCardingWorld .... DONE!")