Skip to content

Commit

Permalink
feature: add inspectNetwork
Browse files Browse the repository at this point in the history
  • Loading branch information
DEMARES Timothee committed Oct 3, 2024
1 parent fcfb444 commit 7bd89ef
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
11 changes: 11 additions & 0 deletions app/adapter/exception/app_exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,14 @@ class EcoindexError(AppError):

class EcoindexScraperStatusError(EcoindexError):
pass


# Inspect Network


class InspectNetworkError(AppError):
pass


class AnalyseMustBeDoneFirstError(AppError):
pass
Empty file.
57 changes: 57 additions & 0 deletions app/core/inspect_network/count_requests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from playwright.sync_api import sync_playwright

from app.adapter.exception.app_exception import AnalyseMustBeDoneFirstError
from app.core.inspect_network.schemas import NetworkRequest


class InspectNetWork:
def __init__(self, url: str) -> None:
self.url = url
self._total_requests: int = 0
self._js_requests: int = 0
self._css_requests: int = 0
self._is_analysed: bool = False

def analyse(self) -> None:
if self._is_analysed is True:
return

with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
page = context.new_page()

page.on("request", self._handle_request)

page.goto(self.url)

page.wait_for_load_state("networkidle")

browser.close()

self._is_analysed = True

def get_result(self) -> NetworkRequest:
if self._is_analysed is False:
raise AnalyseMustBeDoneFirstError("use InspectNetWork.analyse() before")

return NetworkRequest(
total=self._total_requests,
js=self._js_requests,
css=self._css_requests,
)

def _handle_request(self, request):
self._total_requests += 1

if request.resource_type == "script":
self._js_requests += 1
elif request.resource_type == "stylesheet":
self._css_requests += 1


# Exemple d'utilisation
url_to_analyze = "https://www.francetravail.fr/accueil"
inpect = InspectNetWork(url=url_to_analyze)
inpect.analyse()
print(inpect.get_result())
7 changes: 7 additions & 0 deletions app/core/inspect_network/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from pydantic import BaseModel


class NetworkRequest(BaseModel):
total: int
js: int
css: int

0 comments on commit 7bd89ef

Please sign in to comment.