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.

277 lines
9.3 KiB

1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'Helium'
  2. '''
  3. AnonymousMarketplace Marketplace Crawler (Selenium)
  4. this is a small marketplace so next page links are not coded in
  5. '''
  6. from selenium import webdriver
  7. from selenium.common.exceptions import NoSuchElementException
  8. from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
  9. from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
  10. from selenium.webdriver.firefox.service import Service
  11. from selenium.webdriver.support.ui import WebDriverWait
  12. from selenium.webdriver.support import expected_conditions as EC
  13. from selenium.webdriver.common.by import By
  14. from PIL import Image
  15. import urllib.parse as urlparse
  16. import os, re, time
  17. from datetime import date
  18. import subprocess
  19. import configparser
  20. from bs4 import BeautifulSoup
  21. from MarketPlaces.Initialization.prepare_parser import new_parse
  22. from MarketPlaces.AnonymousMarketplace.parser import anonymous_links_parser
  23. from MarketPlaces.Utilities.utilities import cleanHTML
  24. counter = 1
  25. baseURL = 'http://3fqr7fgjaslhgmeiin5e2ky6ra5xkiafyzg7i36sfcehv3jvpgydteqd.onion/'
  26. # Opens Tor Browser, crawls the website, then parses, then closes tor
  27. #acts like the main method for the crawler, another function at the end of this code calls this function later
  28. def startCrawling():
  29. mktName = getMKTName()
  30. driver = getAccess()
  31. if driver != 'down':
  32. try:
  33. # login(driver)
  34. crawlForum(driver)
  35. except Exception as e:
  36. print(driver.current_url, e)
  37. closeDriver(driver)
  38. new_parse(mktName, baseURL, True)
  39. # Returns the name of the website
  40. #return: name of site in string type
  41. def getMKTName():
  42. name = 'AnonymousMarketplace'
  43. return name
  44. # Return the base link of the website
  45. #return: url of base site in string type
  46. def getFixedURL():
  47. url = 'http://3fqr7fgjaslhgmeiin5e2ky6ra5xkiafyzg7i36sfcehv3jvpgydteqd.onion/'
  48. return url
  49. # Closes Tor Browser
  50. #@param: current selenium driver
  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 MarketPlaces.Initialization.markets_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", False)
  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. #the driver 'gets' the url, attempting to get on the site, if it can't access return 'down'
  90. #return: return the selenium driver or string 'down'
  91. def getAccess():
  92. url = getFixedURL()
  93. driver = createFFDriver()
  94. try:
  95. driver.get(url)
  96. return driver
  97. except:
  98. driver.close()
  99. return 'down'
  100. # Manual captcha solver, waits fora specific element so that the whole page loads, finds the input box, gets screenshot of captcha
  101. # then allows for manual solving of captcha in the terminal
  102. #@param: current selenium web driver
  103. def login(driver):
  104. # wait for page to show up (This Xpath may need to change based on different seed url)
  105. WebDriverWait(driver, 100).until(EC.visibility_of_element_located(
  106. (By.ID, "woocommerce_product_categories-2")))
  107. # Saves the crawled html page, makes the directory path for html pages if not made
  108. def savePage(driver, page, url):
  109. cleanPage = cleanHTML(driver, page)
  110. filePath = getFullPathName(url)
  111. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  112. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  113. return
  114. # Gets the full path of the page to be saved along with its appropriate file name
  115. #@param: raw url as crawler crawls through every site
  116. def getFullPathName(url):
  117. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  118. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  119. fileName = getNameFromURL(url)
  120. if isDescriptionLink(url):
  121. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  122. else:
  123. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  124. return fullPath
  125. # Creates the file name from passed URL, gives distinct name if can't be made unique after cleaned
  126. #@param: raw url as crawler crawls through every site
  127. def getNameFromURL(url):
  128. global counter
  129. name = ''.join(e for e in url if e.isalnum())
  130. if (name == ''):
  131. name = str(counter)
  132. counter = counter + 1
  133. return name
  134. # returns list of urls, here is where you can list the different urls of interest, the crawler runs through this list
  135. #in this example, there are a couple of categories some threads fall under such as
  136. # Guides and Tutorials, Digital Products, and Software and Malware
  137. #as you can see they are categories of products
  138. def getInterestedLinks():
  139. links = []
  140. # home
  141. links.append('http://3fqr7fgjaslhgmeiin5e2ky6ra5xkiafyzg7i36sfcehv3jvpgydteqd.onion/')
  142. return links
  143. # gets links of interest to crawl through, iterates through list, where each link is clicked and crawled through
  144. #topic and description pages are crawled through here, where both types of pages are saved
  145. #@param: selenium driver
  146. def crawlForum(driver):
  147. print("Crawling the AnonymousMarketplace market")
  148. linksToCrawl = getInterestedLinks()
  149. i = 0
  150. while i < len(linksToCrawl):
  151. link = linksToCrawl[i]
  152. print('Crawling :', link)
  153. try:
  154. has_next_page = True
  155. count = 0
  156. while has_next_page:
  157. try:
  158. driver.get(link)
  159. except:
  160. driver.refresh()
  161. html = driver.page_source
  162. savePage(driver, html, link)
  163. list = productPages(html)
  164. for item in list:
  165. itemURL = urlparse.urljoin(baseURL, str(item))
  166. try:
  167. driver.get(itemURL)
  168. except:
  169. driver.refresh()
  170. savePage(driver, driver.page_source, item)
  171. driver.back()
  172. # comment out
  173. # break
  174. # comment out
  175. if count == 1:
  176. break
  177. #left in in case site changes
  178. try:
  179. link = driver.find_element(by=By.LINK_TEXT, value="").get_attribute('href')
  180. if link == "":
  181. raise NoSuchElementException
  182. count += 1
  183. except NoSuchElementException:
  184. has_next_page = False
  185. except Exception as e:
  186. print(link, e)
  187. i += 1
  188. print("Crawling the AnonymousMarketplace market done.")
  189. # Returns 'True' if the link is a description link
  190. #@param: url of any url crawled
  191. #return: true if is a description page, false if not
  192. def isDescriptionLink(url):
  193. if '/product/' in url:
  194. return True
  195. return False
  196. # Returns True if the link is a listingPage link
  197. #@param: url of any url crawled
  198. #return: true if is a Listing page, false if not
  199. def isListingLink(url):
  200. if 'category' in url:
  201. return True
  202. return False
  203. # calling the parser to define the links, the html is the url of a link from the list of interested link list
  204. #@param: link from interested link list ie. getInterestingLinks()
  205. #return: list of description links that should be crawled through
  206. def productPages(html):
  207. soup = BeautifulSoup(html, "html.parser")
  208. return anonymous_links_parser(soup)
  209. # Drop links that "signout"
  210. # def isSignOut(url):
  211. # #absURL = urlparse.urljoin(url.base_url, url.url)
  212. # if 'signout' in url.lower() or 'logout' in url.lower():
  213. # return True
  214. #
  215. # return False
  216. def crawler():
  217. startCrawling()
  218. # print("Crawling and Parsing BestCardingWorld .... DONE!")