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.

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