[Python] Request is still present after clearing with request.clear()

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Selenium Wire to monitor network requests while visiting the same website multiple times in a single Selenium session. I have a function that waits for a specific request to appear and raises an exception if it does not:

    class SeleniumExtended:

    def __init__(self, driver):
    self.driver=driver
    self.default_timeout=15
    self.misc= misc_selenium(self.driver)
    self.original_interceptor = None


    def wait_until_request_appeared(self, request_method, request_name, timeout=30):

    self.driver.requests.clear()


    start_time = time.time()

    while time.time() - start_time < timeout:
    for request in self.driver.requests:
    if request.method == request_method and request_name in request.url:
    return request

    time.sleep(0.5) #
    raise TimeoutException(
    f"Desired request '{request_name}' with method '{request_method}' did not appear within {timeout} seconds.")


    Before reloading the page, I use the following function to clear old requests:

    def clear_requests(self):

    self.driver.requests.clear()


    On the first visit to the page, if the request does not appear, wait_until_request_appeared fails correctly. However, after the second visit, if the request appeared on the first visit but not on the second, wait_until_request_appeared still succeeds when it should fail. likely because self.driver.requests.clear() is not actually removing old requests, as the function detects the request from the previous visit.

    How am I supposed to debug this?

    With the functions above I tried:

    extended.wait_until_request_appeared("POST", "callback")

    self.driver.get("https://www.flipkart.com/images-nose-3-steao-remove-blackheads-pack-2/p/itmf1cedd4531e1e?pid=FCPGJGGYKJJBRJ9B&lid=LSTFCPGJGGYKJJBRJ9BPWP6VP&marketplace=FLIPKART&cmpid=content_face-pack_8965229628_gmc)`


    This is the for the first instance. function passes as expected

    Then for the 2nd visit. Where the request does not appear and I clear the requests before re-entering:

    extended.clear_requests()

    time.sleep(5)

    extended.wait_until_request_appeared("POST", "callback")

    self.driver.get("https://www.flipkart.com/images-nose-3-steao-remove-blackheads-pack-2/p/itmf1cedd4531e1e?pid=FCPGJGGYKJJBRJ9B&lid=LSTFCPGJGGYKJJBRJ9BPWP6VP&marketplace=FLIPKART&cmpid=content_face-pack_8965229628_gmc)`


    Result: Function passes succesfully when it shouldn;t

    expected outcome: Function should fail because the request did not appear

    Continue reading...

Compartilhe esta Página