sel_server.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from datetime import datetime
  2. import os
  3. import sys
  4. from selenium import webdriver
  5. from selenium.webdriver.common.by import By
  6. from selenium.webdriver.support.ui import WebDriverWait, Select
  7. from selenium.webdriver.support import expected_conditions as EC
  8. from selenium.webdriver.common.keys import Keys
  9. from selenium.webdriver.remote.webdriver import WebDriver
  10. import time
  11. import rpyc
  12. from rpyc.utils.server import ThreadedServer # or ForkingServer
  13. from bs4 import BeautifulSoup
  14. import json
  15. def send(driver, cmd, params={}):
  16. resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
  17. url = driver.command_executor._url + resource
  18. body = json.dumps({'cmd': cmd, 'params': params})
  19. response = driver.command_executor._request('POST', url, body)
  20. # if response['status']:
  21. # raise Exception(response.get('value'))
  22. return response.get('value')
  23. def add_script(driver, script):
  24. send(driver, "Page.addScriptToEvaluateOnNewDocument", {"source": script})
  25. def init_webdriver():
  26. WebDriver.add_script = add_script
  27. dir_path = os.path.dirname(os.path.realpath(__file__))
  28. options = webdriver.ChromeOptions()
  29. driver = webdriver.Chrome( chrome_options=options)
  30. return driver
  31. #global driver
  32. class MyService(rpyc.Service):
  33. def process(self,url):
  34. self.driver.add_script('const setProperty = () => { Object.defineProperty(navigator, "webdriver", { get: () => false, }); }; setProperty();')
  35. print('add url.............')
  36. print(self.driver)
  37. def __init__(self):
  38. self.driver = None
  39. try:
  40. self.driver = init_webdriver()
  41. print(self.driver )
  42. except Exception as e:
  43. raise e
  44. finally:
  45. True
  46. pass
  47. def exposed_get_url(self,url):
  48. self.driver.add_script('const setProperty = () => { Object.defineProperty(navigator, "webdriver", { get: () => false, }); }; setProperty();')
  49. print('add url.............')
  50. print(self.driver)
  51. self.driver.get(url)
  52. # txt=self.driver.find_element_by_xpath("//div[@id='json']").text
  53. print(self.driver.page_source)
  54. soup = BeautifulSoup(self.driver.page_source,features="lxml")
  55. dict_from_json = json.loads(soup.find("body").text)
  56. return dict_from_json
  57. # return json.loads(self.driver.page_source)
  58. if __name__ == "__main__":
  59. server = ThreadedServer(MyService(), port = 12345,protocol_config={
  60. 'allow_public_attrs': True,
  61. })
  62. server.start()