Skip to content

Instantly share code, notes, and snippets.

@DiTo97
Last active January 10, 2024 05:34
Show Gist options
  • Save DiTo97/3bccf99a1040d4702aaedd9399409382 to your computer and use it in GitHub Desktop.
Save DiTo97/3bccf99a1040d4702aaedd9399409382 to your computer and use it in GitHub Desktop.

Revisions

  1. DiTo97 revised this gist Jan 10, 2024. 1 changed file with 0 additions and 3 deletions.
    3 changes: 0 additions & 3 deletions python-to-js-webserver.py
    Original file line number Diff line number Diff line change
    @@ -54,9 +54,6 @@ def close(self) -> None:
    def execute(self, script: str) -> Any:
    return self.webdriver.execute_script(script)

    async def async_execute(self, script: str) -> Any:
    return self.webdriver.execute_async_script(script)


    if __name__ == "__main__":
    myserver = MyServer("localhost", 8000, None)
  2. DiTo97 revised this gist Jan 10, 2024. 1 changed file with 0 additions and 4 deletions.
    4 changes: 0 additions & 4 deletions python-to-js-webserver.py
    Original file line number Diff line number Diff line change
    @@ -5,7 +5,6 @@
    - https://stackoverflow.com/a/39607115
    """
    import http.server
    import pathlib
    import socketserver
    import threading
    from typing import Any
    @@ -14,9 +13,6 @@
    from selenium.webdriver.chrome import options as chromeoptions


    ROOT = pathlib.Path(__file__).parent


    def from_webroot_dir(directory: str | None):
    def closure(*args: Any, **kwargs: Any) -> http.server.SimpleHTTPRequestHandler:
    return http.server.SimpleHTTPRequestHandler(
  3. DiTo97 revised this gist Jan 10, 2024. 1 changed file with 25 additions and 28 deletions.
    53 changes: 25 additions & 28 deletions python-to-js-webserver.py
    Original file line number Diff line number Diff line change
    @@ -11,13 +11,13 @@
    from typing import Any

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.chrome import options as chromeoptions


    ROOT = pathlib.Path(__file__).parent


    def from_webroot_dir(directory: str):
    def from_webroot_dir(directory: str | None):
    def closure(*args: Any, **kwargs: Any) -> http.server.SimpleHTTPRequestHandler:
    return http.server.SimpleHTTPRequestHandler(
    *args, directory=directory, **kwargs
    @@ -27,33 +27,32 @@ def closure(*args: Any, **kwargs: Any) -> http.server.SimpleHTTPRequestHandler:


    class MyServer:
    def __init__(self, host: str = "localhost", port: int = 8000):
    self.httpd = socketserver.TCPServer((host, port), from_webroot("webroot"))
    self.server_thread = threading.Thread(target=self.httpd.serve_forever)
    def __init__(self, host: str = "localhost", port: int = 8000, webroot: str | None = None):
    self.server = socketserver.TCPServer((host, port), from_webroot_dir(webroot))
    self.executor = threading.Thread(target=self.server.serve_forever)

    def start(self):
    # Start the server in a new thread
    self.server_thread.start()
    def begin(self) -> None:
    self.executor.start()

    def close(self) -> None:
    self.server.shutdown()
    self.executor.join()

    def stop(self):
    # Stop the server and wait for the server thread to finish
    self.httpd.shutdown()
    self.server_thread.join()

    class MyBrowser:
    def __init__(self, host: str, port: int) -> None:
    self.URL = f"http://{host}:{port}"

    options = Options()
    options = chromeoptions.Options()
    options.add_argument("--headless")

    self.webdriver = webdriver.Chrome(options=options)

    def get(self, path: str):
    endpoint = f"{self.URL}/{path}"
    def get(self, resource: str) -> None:
    endpoint = f"{self.URL}/{resource}"
    self.webdriver.get(endpoint)

    def quit(self):
    def close(self) -> None:
    self.webdriver.quit()

    def execute(self, script: str) -> Any:
    @@ -62,24 +61,22 @@ def execute(self, script: str) -> Any:
    async def async_execute(self, script: str) -> Any:
    return self.webdriver.execute_async_script(script)


    if __name__ == "__main__":
    # Usage
    server = MyServer("localhost", 8000)
    server.start()
    myserver = MyServer("localhost", 8000, None)
    myserver.begin()

    browser = MyBrowser("localhost", 8000)
    mybrowser = MyBrowser("localhost", 8000)

    try:
    browser.get("index.html") # Navigate to the local HTML file

    X = browser.execute("return X;")
    helloworld = browser.execute("return printHelloWorld();")
    mybrowser.get("index.html")

    print(X, helloworld) # Output: The value of the global JavaScript variable
    X = mybrowser.execute("return X;")
    helloworld = mybrowser.execute("return helloworld();")

    # Do something with the browser...
    print(X, helloworld)
    except Exception as x:
    print(x)
    finally:
    browser.quit()
    server.stop()
    mybrowser.close()
    myserver.close()
  4. DiTo97 revised this gist Jan 10, 2024. 1 changed file with 6 additions and 0 deletions.
    6 changes: 6 additions & 0 deletions python-to-js-webserver.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,9 @@
    """A simple python-to-JS HTTP web server from a specific webroot
    For more information on python-to-JS transfer possibilities, see the following resources:
    - https://stackoverflow.com/questions/22554313/send-captured-images-from-python-server-to-javascript-client
    - https://stackoverflow.com/a/39607115
    """
    import http.server
    import pathlib
    import socketserver
  5. DiTo97 created this gist Jan 10, 2024.
    16 changes: 16 additions & 0 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    <!DOCTYPE html>
    <html>

    <head>
    <script type="text/javascript">
    const X = "I am X";

    function helloworld() {
    return "Hello world";
    }
    </script>
    </head>

    <body></body>

    </html>
    79 changes: 79 additions & 0 deletions python-to-js-webserver.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,79 @@
    import http.server
    import pathlib
    import socketserver
    import threading
    from typing import Any

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options


    ROOT = pathlib.Path(__file__).parent


    def from_webroot_dir(directory: str):
    def closure(*args: Any, **kwargs: Any) -> http.server.SimpleHTTPRequestHandler:
    return http.server.SimpleHTTPRequestHandler(
    *args, directory=directory, **kwargs
    )

    return closure


    class MyServer:
    def __init__(self, host: str = "localhost", port: int = 8000):
    self.httpd = socketserver.TCPServer((host, port), from_webroot("webroot"))
    self.server_thread = threading.Thread(target=self.httpd.serve_forever)

    def start(self):
    # Start the server in a new thread
    self.server_thread.start()

    def stop(self):
    # Stop the server and wait for the server thread to finish
    self.httpd.shutdown()
    self.server_thread.join()

    class MyBrowser:
    def __init__(self, host: str, port: int) -> None:
    self.URL = f"http://{host}:{port}"

    options = Options()
    options.add_argument("--headless")

    self.webdriver = webdriver.Chrome(options=options)

    def get(self, path: str):
    endpoint = f"{self.URL}/{path}"
    self.webdriver.get(endpoint)

    def quit(self):
    self.webdriver.quit()

    def execute(self, script: str) -> Any:
    return self.webdriver.execute_script(script)

    async def async_execute(self, script: str) -> Any:
    return self.webdriver.execute_async_script(script)

    if __name__ == "__main__":
    # Usage
    server = MyServer("localhost", 8000)
    server.start()

    browser = MyBrowser("localhost", 8000)

    try:
    browser.get("index.html") # Navigate to the local HTML file

    X = browser.execute("return X;")
    helloworld = browser.execute("return printHelloWorld();")

    print(X, helloworld) # Output: The value of the global JavaScript variable

    # Do something with the browser...
    except Exception as x:
    print(x)
    finally:
    browser.quit()
    server.stop()
    1 change: 1 addition & 0 deletions requirements.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    selenium~=4.16.0