首页 > 解决方案 > Can't deal with path

问题描述

I need to load the profile in Chrome using Python Selenium Webdriver. Everyting works fine when I use the direct path like this:

options.add_argument("user-data-dir=C:\path_to_folder_with_myprogram_user_data_folder_is_aready_there\User Data") 

But I plan to use my code on several different PC, so my program should detect the path. I need to detect and insert path to this part of code:

options.add_argument("user-data-dir=C:\\Path") #Path to my user data folder which is in my program folder

I have a problem because I don't know how to get the path from the variable and insert it in 'user-data-dir= '. The variable "user_data_dir" contains the correct path, but when I'm trying to use it, the quotes ruins everything. Without the quotes it works neither.

options = Options()    
user_data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'User Data')
print (user_data_dir)
options.add_argument(r'user-data-dir=user_data_dir') 
driver = webdriver.Chrome(executable_path=os.path.join(retval, 'webdrivers\chromedriver.exe'), options=options) 

标签: pythonselenium-webdriverpath

解决方案


尝试这个,

options = Options()    
user_data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'User Data')
print (user_data_dir)
options.add_argument(r'user-data-dir='+user_data_dir) 
driver = webdriver.Chrome(executable_path=os.path.join(retval, 'webdrivers\chromedriver.exe'), options=options) 

推荐阅读