代码之家  ›  专栏  ›  技术社区  ›  sudoExclamationExclamation

如何在CDP模式下在Selenium Base中设置窗口大小?

  •  1
  • sudoExclamationExclamation  · 技术社区  · 4 月前

    我正在使用 SeleniumBase 在CDP模式下。

    我正在想如何在网站加载后在CDP模式下设置窗口大小?

    如果我使用非CDP函数 sb.set_window_size(x,y) ,然后它被检测为bot runtimeEnableLeak 用于在上打开devtools https://bot-detector.rebrowser.net :

    enter image description here

    我试过了 sb.cdp.set_window_size(x,y) 但该函数似乎不存在,因为它崩溃了:

    sb.cdp.set_window_size(x,y)
    AttributeError: 'types.SimpleNamespace' object has no attribute 'set_window_size'
    

    编辑: 我能够找到一个解决方法,使用 sb.cdp.set_window_rect :

    [screenwidth,screenheight,innerwidth,innerheight,scrollwidth,scrollheight] = sb.cdp.evaluate("return [window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, document.documentElement.scrollWidth, document.documentElement.scrollHeight];")
    
    print(f"Size: {screenwidth}, {screenheight}, {innerwidth}, {innerheight}, {scrollwidth}, {scrollheight}")
    
    sb.cdp.set_window_rect(0,0,scrollwidth + screenwidth - innerwidth, scrollheight + screenheight - innerheight + 100)
    
    print(f"Sleeping for some time...")
    sb.sleep(random.randint(5, 8))
    

    有更好的办法吗?

    1 回复  |  直到 4 月前
        1
  •  1
  •   Michael Mintz    4 月前

    使用 sb.cdp.set_window_rect(x, y, width, height) (所有4个参数都需要设置。)例如:

    from seleniumbase import SB
    
    with SB(uc=True, test=True) as sb:
        url = "https://bot-detector.rebrowser.net/"
        sb.activate_cdp_mode(url)
        sb.cdp.set_window_rect(10, 10, 1200, 700)
        sb.sleep(10)
    
    推荐文章