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.

276 lines
8.3 KiB

  1. __author__ = 'chris'
  2. '''
  3. WeTheNorth 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. config = configparser.ConfigParser()
  23. config.read('../../setup.ini')
  24. counter = 1
  25. baseURL = 'http://ilr3qzubfnx33vbhal7l5coo4ftqlkv2tboph4ujog5crz6m5ua2b2ad.onion/'
  26. # Opens Tor Browser, crawls the website
  27. def startCrawling():
  28. # Opening tor beforehand gives "Tor exited during startup error"
  29. # opentor()
  30. marketName = getMarketName()
  31. driver = getAccess()
  32. # Captcha
  33. input("Press ENTER when website has loaded")
  34. if driver != 'down':
  35. try:
  36. # Robinhood doesn't need login
  37. # login(driver)
  38. crawlForum(driver)
  39. except Exception as e:
  40. print(driver.current_url, e)
  41. closetor(driver)
  42. new_parse(marketName, baseURL, False)
  43. # Opens Tor Browser
  44. def opentor():
  45. global pid
  46. print("Connecting Tor...")
  47. pro = subprocess.Popen(config.get('TOR', 'firefox_binary_path'))
  48. pid = pro.pid
  49. time.sleep(7.5)
  50. input('Tor Connected. Press ENTER to continue\n')
  51. return
  52. # Login is not needed in Robinhood
  53. def login(driver):
  54. pass
  55. # Returns the name of the website
  56. def getMarketName():
  57. name = 'RobinhoodMarket'
  58. return name
  59. # Return the link of the website
  60. def getFixedURL():
  61. url = 'http://ilr3qzubfnx33vbhal7l5coo4ftqlkv2tboph4ujog5crz6m5ua2b2ad.onion/'
  62. return url
  63. # Closes Tor Browser
  64. def closetor(driver):
  65. # global pid
  66. # os.system("taskkill /pid " + str(pro.pid))
  67. # os.system("taskkill /t /f /im tor.exe")
  68. print('Closing Tor...')
  69. driver.quit()
  70. time.sleep(3)
  71. return
  72. # Creates FireFox 'driver' and configure its 'Profile'
  73. # to use Tor proxy and socket
  74. def createFFDriver():
  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. return driver
  100. def getAccess():
  101. url = getFixedURL()
  102. driver = createFFDriver()
  103. input('Tor Connected. Press ENTER to continue\n')
  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(page, url):
  112. cleanPage = cleanHTML(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 CURRENT_DATE
  120. fileName = getNameFromURL(url)
  121. if isDescriptionLink(url):
  122. fullPath = r'..\RobinhoodMarket\HTML_Pages\\' + CURRENT_DATE + r'\\Description\\' + fileName + '.html'
  123. else:
  124. fullPath = r'..\RobinhoodMarket\HTML_Pages\\' + CURRENT_DATE + r'\\Listing\\' + fileName + '.html'
  125. return fullPath
  126. # Creates the file name from passed URL
  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. def getInterestedLinks():
  135. links = []
  136. # Hacking
  137. links.append('http://ilr3qzubfnx33vbhal7l5coo4ftqlkv2tboph4ujog5crz6m5ua2b2ad.onion/product-category/hacking/')
  138. # Other Software
  139. links.append('http://ilr3qzubfnx33vbhal7l5coo4ftqlkv2tboph4ujog5crz6m5ua2b2ad.onion/product-category/other-software/')
  140. return links
  141. def crawlForum(driver):
  142. print("Crawling the Robinhood market")
  143. linksToCrawl = getInterestedLinks()
  144. visited = set(linksToCrawl)
  145. initialTime = time.time()
  146. i = 0
  147. count = 0
  148. while i < len(linksToCrawl):
  149. link = linksToCrawl[i]
  150. print('Crawling :', link)
  151. try:
  152. try:
  153. driver.get(link)
  154. except:
  155. driver.refresh()
  156. html = driver.page_source
  157. savePage(html, link)
  158. has_next_page = True
  159. while has_next_page:
  160. list = productPages(html)
  161. for item in list:
  162. itemURL = urlparse.urljoin(baseURL, str(item))
  163. try:
  164. driver.get(itemURL)
  165. except:
  166. driver.refresh()
  167. savePage(driver.page_source, item)
  168. driver.back()
  169. # comment out
  170. # break
  171. # comment out
  172. # if count == 1:
  173. # count = 0
  174. # break
  175. # go to next page of market
  176. try:
  177. nav = driver.find_element(by=By.XPATH, value="//a[@class='next page-numbers']")
  178. link = nav.get_attribute('href')
  179. if link == "":
  180. raise NoSuchElementException
  181. try:
  182. driver.get(link)
  183. except:
  184. driver.refresh()
  185. html = driver.page_source
  186. savePage(html, link)
  187. count += 1
  188. except NoSuchElementException:
  189. has_next_page = False
  190. except Exception as e:
  191. print(link, e)
  192. i += 1
  193. # finalTime = time.time()
  194. # print finalTime - initialTime
  195. input("Crawling Robinhood market done successfully. Press ENTER to continue\n")
  196. # Returns 'True' if the link is Topic link
  197. def isDescriptionLink(url):
  198. if 'product' in url and 'category' not in url:
  199. return True
  200. return False
  201. # Returns True if the link is a listingPage link
  202. def isListingLink(url):
  203. if 'category=' in url:
  204. return True
  205. return False
  206. # calling the parser to define the links
  207. def productPages(html):
  208. soup = BeautifulSoup(html, "html.parser")
  209. return Robinhood_links_parser(soup)
  210. def crawler():
  211. startCrawling()
  212. # print("Crawling and Parsing BestCardingWorld .... DONE!")
  213. if __name__ == '__main__':
  214. startCrawling()