标签 playwright 下的文章

[2025-02-10 13:40:41] [ERROR] [unknown:0] [0] got error:TimeoutError: elementHandle.hover: Timeout 2000ms exceeded.
Call log:

  • attempting hover action
    2 × waiting for element to be visible and stable

    • element is visible and stable
    • scrolling into view if needed
    • done scrolling
    • performing hover action
    • from
      subtree intercepts pointer events
    • retrying hover action
    • waiting 20ms
    • × waiting for element to be visible and stable

      • element is visible and stable
      • scrolling into view if needed
      • done scrolling
      • performing hover action
      • from
        subtree intercepts pointer events
    • retrying hover action

      • waiting 100ms
    • × waiting for element to be visible and stable

      • element is visible and stable
      • scrolling into view if needed
      • done scrolling
      • performing hover action
      • from
        subtree intercepts pointer events
    • retrying hover action

      • waiting 500ms

<div id="slideBg"> 拦截了指针事件(intercepts pointer events)

from playwright.sync_api import sync_playwright
import time
 
 
with sync_playwright() as p:
    '''
    防止被浏览器检测的处理方法
    '''
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    #下载地址 https://github.com/kingname/stealth.min.js/blob/main/stealth.min.js
    with open('stealth.min.js','r') as f:
        js=f.read()
    page.add_init_script(js)
    
    page.goto('https://bot.sannysoft.com/')
    
    time.sleep(1000)
 
    browser.close()

import sys
from pathlib import Path

# 设置一个跨平台的统一路径
def get_playwright_browsers_path():
    # 获取用户主目录

    home_dir = Path.home()

    # 在主目录下创建一个固定的 Playwright 浏览器路径
    playwright_path = home_dir / ".playwright_browsers"

    # 确保路径存在
    playwright_path.mkdir(parents=True, exist_ok=True)

    return str(playwright_path)

# 动态设置浏览器路径
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = get_playwright_browsers_path()

def ensure_browser_installed():
    try:
        from playwright.__main__ import main as playwright_main
        playwright_main()  # 自动安装 Chromium
    except Exception as e:
        print(f"Error during Playwright installation: {e}")
if __name__ == "__main__":
    # check args
    args = sys.argv
    if len(args)>1 and args[1] == 'install':
        ensure_browser_installed()
    app = QApplication(sys.argv)
    main_window = URLFetcherApp()
    main_window.show()
    sys.exit(app.exec_())

打包之后运行

main.exe install

browser = p.chromium.launch(headless=False)  # 禁用无头模式以显示浏览器窗口
context = browser.new_context(
    user_agent=None,
    viewport={"width": 1500, "height": 800},
)

改为

browser = p.chromium.launch(headless=False)  # 禁用无头模式以显示浏览器窗口
context = browser.new_context(
    no_viewport=True,  # 使用浏览器的默认视口
    user_agent=None,  # 使用浏览器的默认 User-Agent
)