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.
A simple python-to-JS HTTP web server from a specific webroot
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
const X = "I am X";
function helloworld() {
return "Hello world";
}
</script>
</head>
<body></body>
</html>
"""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 socketserver
import threading
from typing import Any
from selenium import webdriver
from selenium.webdriver.chrome import options as chromeoptions
def from_webroot_dir(directory: str | None):
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, webroot: str | None = None):
self.server = socketserver.TCPServer((host, port), from_webroot_dir(webroot))
self.executor = threading.Thread(target=self.server.serve_forever)
def begin(self) -> None:
self.executor.start()
def close(self) -> None:
self.server.shutdown()
self.executor.join()
class MyBrowser:
def __init__(self, host: str, port: int) -> None:
self.URL = f"http://{host}:{port}"
options = chromeoptions.Options()
options.add_argument("--headless")
self.webdriver = webdriver.Chrome(options=options)
def get(self, resource: str) -> None:
endpoint = f"{self.URL}/{resource}"
self.webdriver.get(endpoint)
def close(self) -> None:
self.webdriver.quit()
def execute(self, script: str) -> Any:
return self.webdriver.execute_script(script)
if __name__ == "__main__":
myserver = MyServer("localhost", 8000, None)
myserver.begin()
mybrowser = MyBrowser("localhost", 8000)
try:
mybrowser.get("index.html")
X = mybrowser.execute("return X;")
helloworld = mybrowser.execute("return helloworld();")
print(X, helloworld)
except Exception as x:
print(x)
finally:
mybrowser.close()
myserver.close()
selenium~=4.16.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment