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