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.

271 lines
8.1 KiB

  1. __author__ = 'chris'
  2. '''
  3. RobinhoodMarket Market 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. import configparser
  18. from bs4 import BeautifulSoup
  19. from MarketPlaces.Initialization.prepare_parser import new_parse
  20. from MarketPlaces.RobinhoodMarket.parser import Robinhood_links_parser
  21. from MarketPlaces.Utilities.utilities import cleanHTML
  22. counter = 1
  23. baseURL = 'http://ilr3qzubfnx33vbhal7l5coo4ftqlkv2tboph4ujog5crz6m5ua2b2ad.onion/'
  24. # Opens Tor Browser, crawls the website
  25. def startCrawling():
  26. # Opening tor beforehand gives "Tor exited during startup error"
  27. # opentor()
  28. marketName = getMKTName()
  29. driver = getAccess()
  30. if driver != 'down':
  31. try:
  32. # Captcha
  33. input("Press ENTER when website has loaded")
  34. # Robinhood doesn't need login
  35. # login(driver)
  36. crawlForum(driver)
  37. except Exception as e:
  38. print(driver.current_url, e)
  39. closetor(driver)
  40. new_parse(marketName, baseURL, True)
  41. # Opens Tor Browser
  42. def opentor():
  43. from MarketPlaces.Initialization.markets_mining import config
  44. global pid
  45. print("Connecting Tor...")
  46. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  47. pid = pro.pid
  48. time.sleep(7.5)
  49. input('Tor Connected. Press ENTER to continue\n')
  50. return
  51. # Login is not needed in Robinhood
  52. def login(driver):
  53. pass
  54. # Returns the name of the website
  55. def getMKTName():
  56. name = 'RobinhoodMarket'
  57. return name
  58. # Return the link of the website
  59. def getFixedURL():
  60. url = 'http://ilr3qzubfnx33vbhal7l5coo4ftqlkv2tboph4ujog5crz6m5ua2b2ad.onion/'
  61. return url
  62. # Closes Tor Browser
  63. def closetor(driver):
  64. # global pid
  65. # os.system("taskkill /pid " + str(pro.pid))
  66. # os.system("taskkill /t /f /im tor.exe")
  67. print('Closing Tor...')
  68. driver.quit()
  69. time.sleep(3)
  70. return
  71. # Creates FireFox 'driver' and configure its 'Profile'
  72. # to use Tor proxy and socket
  73. def createFFDriver():
  74. from MarketPlaces.Initialization.markets_mining import config
  75. ff_binary = FirefoxBinary(config.get('TOR', 'firefox_binary_path'))
  76. ff_prof = FirefoxProfile(config.get('TOR', 'firefox_profile_path'))
  77. ff_prof.set_preference("places.history.enabled", False)
  78. ff_prof.set_preference("privacy.clearOnShutdown.offlineApps", True)
  79. ff_prof.set_preference("privacy.clearOnShutdown.passwords", True)
  80. ff_prof.set_preference("privacy.clearOnShutdown.siteSettings", True)
  81. ff_prof.set_preference("privacy.sanitize.sanitizeOnShutdown", True)
  82. ff_prof.set_preference("signon.rememberSignons", False)
  83. ff_prof.set_preference("network.cookie.lifetimePolicy", 2)
  84. ff_prof.set_preference("network.dns.disablePrefetch", True)
  85. ff_prof.set_preference("network.http.sendRefererHeader", 0)
  86. ff_prof.set_preference("permissions.default.image", 3)
  87. ff_prof.set_preference("browser.download.folderList", 2)
  88. ff_prof.set_preference("browser.download.manager.showWhenStarting", False)
  89. ff_prof.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/plain")
  90. ff_prof.set_preference('network.proxy.type', 1)
  91. ff_prof.set_preference("network.proxy.socks_version", 5)
  92. ff_prof.set_preference('network.proxy.socks', '127.0.0.1')
  93. ff_prof.set_preference('network.proxy.socks_port', 9150)
  94. ff_prof.set_preference('network.proxy.socks_remote_dns', True)
  95. ff_prof.set_preference("javascript.enabled", False)
  96. ff_prof.update_preferences()
  97. service = Service(config.get('TOR', 'geckodriver_path'))
  98. driver = webdriver.Firefox(firefox_binary=ff_binary, firefox_profile=ff_prof, service=service)
  99. driver.maximize_window()
  100. return driver
  101. def getAccess():
  102. url = getFixedURL()
  103. driver = createFFDriver()
  104. try:
  105. driver.get(url)
  106. return driver
  107. except:
  108. driver.close()
  109. return 'down'
  110. # Saves the crawled html page
  111. def savePage(driver, page, url):
  112. cleanPage = cleanHTML(driver, page)
  113. filePath = getFullPathName(url)
  114. os.makedirs(os.path.dirname(filePath), exist_ok=True)
  115. open(filePath, 'wb').write(cleanPage.encode('utf-8'))
  116. return
  117. # Gets the full path of the page to be saved along with its appropriate file name
  118. def getFullPathName(url):
  119. from MarketPlaces.Initialization.markets_mining import config, CURRENT_DATE
  120. mainDir = os.path.join(config.get('Project', 'shared_folder'), "MarketPlaces/" + getMKTName() + "/HTML_Pages")
  121. fileName = getNameFromURL(url)
  122. if isDescriptionLink(url):
  123. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Description\\' + fileName + '.html')
  124. else:
  125. fullPath = os.path.join(mainDir, CURRENT_DATE + r'\\Listing\\' + fileName + '.html')
  126. return fullPath
  127. # Creates the file name from passed URL
  128. def getNameFromURL(url):
  129. global counter
  130. name = ''.join(e for e in url if e.isalnum())
  131. if name == '':
  132. name = str(counter)
  133. counter = counter + 1
  134. return name
  135. def getInterestedLinks():
  136. links = []
  137. # Hacking
  138. links.append('http://ilr3qzubfnx33vbhal7l5coo4ftqlkv2tboph4ujog5crz6m5ua2b2ad.onion/product-category/hacking/')
  139. # # Other Software
  140. # links.append('http://ilr3qzubfnx33vbhal7l5coo4ftqlkv2tboph4ujog5crz6m5ua2b2ad.onion/product-category/other-software/')
  141. return links
  142. def crawlForum(driver):
  143. print("Crawling the Robinhood market")
  144. linksToCrawl = getInterestedLinks()
  145. i = 0
  146. while i < len(linksToCrawl):
  147. link = linksToCrawl[i]
  148. print('Crawling :', link)
  149. try:
  150. has_next_page = True
  151. count = 0
  152. while has_next_page:
  153. try:
  154. driver.get(link)
  155. except:
  156. driver.refresh()
  157. html = driver.page_source
  158. savePage(driver, html, link)
  159. list = productPages(html)
  160. for item in list:
  161. itemURL = urlparse.urljoin(baseURL, str(item))
  162. try:
  163. driver.get(itemURL)
  164. except:
  165. driver.refresh()
  166. savePage(driver, driver.page_source, item)
  167. driver.back()
  168. # comment out
  169. # break
  170. # comment out
  171. if count == 1:
  172. break
  173. # go to next page of market
  174. try:
  175. nav = driver.find_element(by=By.XPATH, value="//a[@class='next page-numbers']")
  176. link = nav.get_attribute('href')
  177. if link == "":
  178. raise NoSuchElementException
  179. count += 1
  180. except NoSuchElementException:
  181. has_next_page = False
  182. except Exception as e:
  183. print(link, e)
  184. i += 1
  185. print("Crawling the Robinhood market done.")
  186. # Returns 'True' if the link is Topic link
  187. def isDescriptionLink(url):
  188. if 'product' in url and 'category' not in url:
  189. return True
  190. return False
  191. # Returns True if the link is a listingPage link
  192. def isListingLink(url):
  193. if 'category=' in url:
  194. return True
  195. return False
  196. # calling the parser to define the links
  197. def productPages(html):
  198. soup = BeautifulSoup(html, "html.parser")
  199. return Robinhood_links_parser(soup)
  200. def crawler():
  201. startCrawling()
  202. # print("Crawling and Parsing BestCardingWorld .... DONE!")
  203. if __name__ == '__main__':
  204. startCrawling()