selenium使用用户目录
当你想要读取用户正常浏览器配置(包括某些站点的登录状态)
def get_driver_option(): chrome_options = Options() chrome_options.add_argument('--no-sandbox') # 无头模式 # chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') # chrome_options.add_argument('--window-size=1980,1200') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option('useAutomationExtension', False) # chrome_options.add_argument(r'--user-data-dir=C:\Users\pcan1445\AppData\Local\Google\Chrome\User Data') chrome_options.add_argument(r'--user-data-dir=xxxxxxxxxxxxxxxx\User Data')
但是这样你就不能再开打开浏览器了,所以可以用这么一纵方式复制一份用户目录,复制只要复制i一份就行,这个而函数只执行一次,后面就用第一次生成的那个用户目录就行
def get_driver_option(): chrome_options = Options() chrome_options.add_argument('--no-sandbox') # 无头模式 # chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-dev-shm-usage') # chrome_options.add_argument('--window-size=1980,1200') chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-blink-features=AutomationControlled") chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option('useAutomationExtension', False)src_profile = r"C:\Users\pcan1445\AppData\Local\Google\Chrome\User Data" tmp_profile = tempfile.mkdtemp(prefix="chrome_abc123") # 例如 C:\Temp\chrome_abc123 dst_profile = os.path.join(tmp_profile, "User Data") # 必须叫 User Data shutil.copytree(src_profile, dst_profile, dirs_exist_ok=True) print(dst_profile) chrome_options.add_argument(f"--user-data-dir={dst_profile}") chrome_options.add_argument("--profile-directory=Default") return chrome_options