[Python] i want that my scrips in playwright python should get more better cuz they get banned...

Discussão em 'Python' iniciado por Stack, Julho 31, 2025.

  1. Stack

    Stack Membro Participativo

    I have used this now but for my project but it gets banned in 2 weeks and like browser is get banned only but like i wnat to know that what else can i add to be more non detectable for education and learning purpose , as i am an automation dev,

    i am using playwright python and playwirhgt stealth plugin too so assuming all the basics ones that playwrgiht - stealth sync api gives the page non detection spoof is ok but that is so basic , so i added my scripts but i still need refinements, also i know we can change brwoser profiles like rotation with canvas , font , other values to be changed + human behaviour

    so here is the code , also if someone can give me detailed list that what else i avtually need to rotate in the values , a list give me plz , and also review this code and suggest me anyting else i can add in this ,

    def _init_browser(self):
    # ip.main() # IP configs
    print("----------------------------------------------------------")
    print(" Launching persistent stealth Chromium instance...")

    self.playwright = sync_playwright().start()
    self.context = self.playwright.chromium.launch_persistent_context(
    slow_mo=0,
    locale="en-US",
    timezone_id="Asia/Kolkata",
    geolocation={"longitude": 77.2090, "latitude": 28.6139},
    permissions=["geolocation", "clipboard-read", "clipboard-write"],
    # color_scheme="no-preference", # or "dark" or light
    is_mobile=False,
    reduced_motion="no-preference",
    forced_colors=None, # or "active"
    service_workers="allow", # block
    has_touch=False,
    ignore_https_errors=True,
    user_data_dir=self.user_data_dir,
    devtools=False,
    device_scale_factor=2.0,
    headless=False,
    ignore_default_args=[
    "--enable-automation",
    "--disable-blink-features=AutomationControlled"
    ],
    timeout=SETTINGS.BROWSER_INIT_TIMEOUT,
    traces_dir=traces_dir,
    args=[
    "--no-sandbox",
    "--disable-setuid-sandbox",
    "--disable-infobars",
    "--window-size=1280,800",
    ],
    viewport={"width": 1280, "height":720 },
    user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
    extra_http_headers=steal.headers,
    java_script_enabled=True
    )
    def stealth(page: Page) -> None:
    """
    Applies stealth techniques and JS spoofing to the given page.
    :return: Page itself
    """
    s = Stealth()
    s.apply_stealth_sync(page)
    page.add_init_script(_custom_js_spoof_payload())
    page.add_init_script(Mouse_UI)
    print("[[Stealth scripts and Mouse UI injected]]")
    print("----------------------------------------------------------")


    Mouse_UI = """
    window.addEventListener('DOMContentLoaded', () => {
    const dot = document.createElement('div');
    dot.id = '__mouse_dot__';
    Object.assign(dot.style, {
    position: 'fixed',
    width: '10px',
    height: '10px',
    borderRadius: '65%',
    backgroundColor: 'black',
    zIndex: '2147483647', // Max z-index
    pointerEvents: 'none',
    top: '0px',
    left: '0px',
    transform: 'translate(-50%, -50%)',
    transition: 'top 0.03s linear, left 0.03s linear'
    });
    document.body.appendChild(dot);
    window.addEventListener('mousemove', e => {
    dot.style.left = `${e.clientX}px`;
    dot.style.top = `${e.clientY}px`;
    });
    });
    """

    def _custom_js_spoof_payload():
    """
    Custom js Spoof -------
    :return: payload as String to run as a script.
    """
    return r"""
    (() => {
    // Removing webdriver
    try {
    delete Object.getPrototypeOf(navigator).webdriver;
    } catch (e) {}

    // Canvas Spoofing
    const toDataURL = HTMLCanvasElement.prototype.toDataURL;
    HTMLCanvasElement.prototype.toDataURL = function(...args) {
    const ctx = this.getContext('2d');
    const shift = 2;
    ctx.globalAlpha = 0.9;
    ctx.fillStyle = 'rgba(100,100,100,0.1)';
    ctx.fillRect(shift, shift, this.width - shift*2, this.height - shift*2);
    return toDataURL.apply(this, args);
    };

    // ClientRects Spoofing
    const origGetClientRects = Element.prototype.getClientRects;
    Element.prototype.getClientRects = function() {
    const rects = origGetClientRects.apply(this);
    for (const r of rects) {
    r.x += 0.1; r.y += 0.1;
    r.width += 0.1; r.height += 0.1;
    }
    return rects;
    };

    // AudioContext Spoofing
    const origGetChannelData = AudioBuffer.prototype.getChannelData;
    AudioBuffer.prototype.getChannelData = function() {
    const data = origGetChannelData.apply(this, arguments);
    for (let i = 0; i < data.length; i += 100) {
    data += Math.random() * 1e-7;
    }
    return data;
    };

    // WebRTC Leak Prevention
    function RTCPeerConnectionStub() {
    return {
    createOffer: async () => ({}),
    setLocalDescription: async () => {},
    addIceCandidate: async () => {},
    close: () => {},
    addEventListener: () => {},
    removeEventListener: () => {}
    };
    }
    Object.defineProperty(window, 'RTCPeerConnection', { value: RTCPeerConnectionStub });
    Object.defineProperty(window, 'webkitRTCPeerConnection', { value: RTCPeerConnectionStub });

    // mediaDevices spoof
    Object.defineProperty(navigator, 'mediaDevices', {
    value: {
    enumerateDevices: async () => [
    { kind: 'audioinput', label: 'Microphone', deviceId: 'mic1' },
    { kind: 'videoinput', label: 'Webcam', deviceId: 'cam1' },
    { kind: 'audiooutput', label: 'Speaker', deviceId: 'spk1' }
    ]
    }
    });

    // Hardware Properties
    Object.defineProperty(navigator, 'deviceMemory', { get: () => 16 });
    Object.defineProperty(navigator, 'hardwareConcurrency', { get: () => 4 });

    // Platform spoof (Match with UA)
    Object.defineProperty(navigator, 'platform', { get: () => 'Linux x86_64' });

    // Do Not Track
    // Object.defineProperty(navigator, 'doNotTrack', { get: () => '1' });

    // Screen and Window
    Object.defineProperty(window, 'innerWidth', { get: () => 1301 });
    Object.defineProperty(window, 'innerHeight', { get: () => 724});
    Object.defineProperty(window, 'outerWidth', { get: () => 1301 });
    Object.defineProperty(window, 'outerHeight', { get: () => 724 });

    Object.defineProperty(window.screen, 'width', { get: () => 1301 });
    Object.defineProperty(window.screen, 'height', { get: () => 724 });
    Object.defineProperty(window.screen, 'availWidth', { get: () => 1301 });
    Object.defineProperty(window.screen, 'availHeight', { get: () => 724 });
    //Object.defineProperty(window.screen, 'colorDepth', { get: () => 24 });
    //Object.defineProperty(window.screen, 'pixelDepth', { get: () => 24 });

    // Fake Chrome object to prevent runtime errors
    window.chrome = {
    runtime: {},
    webstore: {}
    };

    // matchMedia override (updated logic)
    const originalMatchMedia = window.matchMedia;
    window.matchMedia = function(query) {
    const forcedMatch = /1301|724|max\-width|min\-width|max\-height|min\-height/.test(query);
    return {
    matches: forcedMatch,
    media: query,
    onchange: null,
    addListener: () => {},
    removeListener: () => {},
    addEventListener: () => {},
    removeEventListener: () => {},
    dispatchEvent: () => false
    };
    };
    })();
    """


    headers = {

    "Origin": "https://web.whatsapp.com",
    "Referer": "https://web.whatsapp.com/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) "
    "Chrome/138.0.0.0 Safari/537.36",
    }


    now do i lack anywhere ? plz help i dont know js but i am doing this in python playwrihgt , like i dont want to deep dive in the js as i may dont need this much right ? also like js is needed for the brwoser scripting or may be at high level they will ask me for js as eval_on_selector like these will need js , so ya help.

    Continue reading...

Compartilhe esta Página