undetected_chromedriver 控制已打开的浏览器


def get_options():
    options = ChromeOptions()
    options.add_argument("--disable-blink-features=AutomationControlled")
    # options.add_experimental_option("excludeSwitches", ["enable-automation"])
    # options.add_experimental_option("useAutomationExtension", False)
    options.add_argument("--disable-extensions")
    options.add_argument("--no-default-browser-check")
    options.add_argument("--no-first-run")
    options.add_argument("--disable-popup-blocking")
    options.add_argument("--disable-default-apps")
    options.add_argument("--disable-infobars")
    # options.add_argument("--disable-gpu")
    # options.add_argument("--disable-notifications")
    options.add_argument("--disable-translate")
    options.add_argument("--disable-device-discovery-notifications")
    options.add_argument("--no-sandbox")
    # options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--window-size=1920x1080")
    options.add_argument("--disable-features=VizDisplayCompositor")
    return options

def getchromeversion():
    if 'win' in sys.platform:
        import winreg
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Google\Chrome\BLBeacon')
        chrome_version = winreg.QueryValueEx(key, 'version')[0]
        return chrome_version
    else:
        from webdriver_manager.utils import get_browser_version_from_os
        browserVersion = get_browser_version_from_os("google-chrome")  # 获取当前系统chrome浏览器的版本号
        print(f'Chrome version is {browserVersion}')
        mainBrowserVersion = browserVersion.split(".")[0]  # 获取chrome浏览器的主版本号
        return browserVersion

def cmd_start_brower(chrome_path, port, user_data_dir):
        # current_file_path = os.path.dirname(os.path.realpath(sys.argv[0]))
        # user_data_dir = os.path.join(current_file_path, "pyppeteer_chrome")  # 浏览器用户配置文件
        chrome_path_temp = chrome_path.replace('\chrome.exe', '')
        start_params = r'cd {} && chrome.exe --remote-debugging-port={} --user-data-dir="{}" --no-first-run --disable-popup-blocking --allow-file-access-from-files --no-default-browser-check'
        os.popen(start_params.format(chrome_path_temp, port, user_data_dir))

def get_session_url(chrome_path, port, user_data_dir):
    url = f'http://127.0.0.1:{port}/json/version'
    try:
        res = requests.get(url)
        print(res.text)
        webSocketDebuggerUrl = json.loads(res.text)['webSocketDebuggerUrl']
    except:
        # 命令行启动
        cmd_start_brower(chrome_path, port, user_data_dir)
        time.sleep(random.randint(4, 6))


def start_brower():
    from undetected_chromedriver import Chrome, ChromeOptions, find_chrome_executable
    user_data_name = "chrome1"
    port = 9315
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
    current_path = os.path.dirname(os.path.realpath(sys.argv[0]))
    # 浏览器用户配置文件
    user_data_dir = os.path.join(current_path, user_data_name)
    # 浏览器版本号
    version = getchromeversion().split('.')[0]
    # 下载驱动
    currentpath = os.path.dirname(os.path.realpath(sys.argv[0]))
    executable_path = os.path.join(currentpath, 'chromedriver_win32', f'chromedriver_{version}.exe')
    if not os.path.exists(executable_path):
        # get_chromedriver_version(path, version) # 在另一篇文章中
        print('自动下载驱动')
    # 浏览器路径
    chrome_path = find_chrome_executable()
    print('executable_path:', executable_path)
    print('user_data_dir:', user_data_dir)
    print('chrome_path:', chrome_path)
    # 检测浏览器是否已打开
    get_session_url(chrome_path, port, user_data_dir)
    option = get_options()
    option.add_argument(fr'--user-data-dir="{user_data_dir}"')
    option.add_argument(f"--user-agent={user_agent}")
    option.debugger_address = f"127.0.0.1:{port}"
    driver = Chrome(options=option, executable_path=executable_path)
    print(driver.title)
    time.sleep(2)
    driver.get('https://blog.youkuaiyun.com/lwdfzr/article/details/135410359')
    time.sleep(random.randint(3, 5))
undetected_chromedriver 通过端口控制已打开的浏览器时,会打开一个多余的空白窗口,

鼠标放在Chrome() 按ctrl+B查看源码,找到这段代码,注释掉

undetected_chromedriver的作者已转移到另一个库nodriver

undetected_chromedriver是一个Python库,用于绕过Chrome浏览器的人机验证。通过安装并使用undetected_chromedriver,您可以在Windows系统上使用undetected_chromedriver实现无人机验证的Chrome下载。 以下是如何在Windows上使用undetected_chromedriver进行Chrome下载的步骤: 1. 首先,确保您已经安装了Python和pip。您可以在命令提示符下运行以下命令来检查是否已经安装: ``` python --version pip --version ``` 如果命令成功运行并显示Python和pip的版本信息,则说明它们已经安装。 2. 打开命令提示符,并运行以下命令来安装undetected_chromedriver: ``` pip install undetected_chromedriver ``` 3. 安装完成后,您可以在Python脚本中导入undetected_chromedriver库,并使用以下代码下载Chrome: ```python import undetected_chromedriver as uc options = uc.ChromeOptions() prefs = { 'profile.default_content_settings.popups': 0, # 禁止弹窗 'download.default_directory': '指定下载位置', # 默认下载位置 'safebrowsing.enabled': 'false' # 取消安全下载 } options.add_experimental_option('prefs', prefs) driver = uc.Chrome(options=options) driver.get('这里改为网址') ``` 在以上代码中,您需要将`指定下载位置`替换为您想要保存Chrome下载文件的实际路径。然后,您可以使用`driver.get()`方法打开您想要下载的网址,并自动下载Chrome。 请注意,以上方法已经经过测试,可以在Windows系统上成功下载Chrome。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值