Change ChromeOptions in an existing webdriver

2020-01-25 02:26发布

Scenario: There is a requirement of downloading files from web hierarchy to local drive under same hierarchy.

Example Web Hierarchy:

Parent 1:  
  Child 1:  
    *File 1  
  Child 2:  
    *File 2  

When downloading File 1, it should store in path 1 - "C:\....\Downloads\Parent 1\Child 1\"

When downloading File 2, it should store in path 2 - "C:\....\Downloads\Parent 1\Child 2\"

Problem:

When I keep "C:....\Downloads\Parent 1\Child 1\" download path in chrome webdriver while initializing webdriver first time in setUp() & download "File 1", it downloads in expected folder. But when I set next "C:....\Downloads\Parent 1\Child 2\" download path in chrome webdriver for downloading File 2 in it, it opens another chrome browser because I am using another webdriver for setting path 2.

Required Solution:

I want to use existing webdriver to set different chrome download paths or any other workaround you can think of.

Current Code:

def setUp(self):  
browser = webdriver.Chrome(chromedriver_path, option_with_path_1_set)

def test_downloadFiles(self):  
\*code to download first file\*  
driver = webdriver.Chrome(chromedriver_path, option_with_path_2_set)  
\*code to download second file\*  

def tearDown(self):  
browser.quit()

Please let me know if you require any additional information.

Thanks in advance!

1条回答
Ridiculous、
2楼-- · 2020-01-25 03:12

When you configure an instance of a ChromeDriver with ChromeOptions to initiate a new Chrome Browser Session the configuration of the ChromeDriver remains unchanged throughout the lifetime of the ChromeDriver and remains uneditable

Even if you are able to extract the ChromeDriver and ChromeSession attributes e.g. Session ID, Cookies and other session attributes from the initiated Browsing Session still you won't be able to change those attributes of the ChromeDriver.

A cleaner way would be to call driver.quit() within tearDown(){} method to close and destroy the ChromeDriver and Chrome Browser instances gracefully and then span a new set of ChromeDriver and Chrome Browser instance with the new set of configurations.

Here you can find a relevant discussion on How can I reconnect to the browser opened by webdriver with selenium?


Update

As @KirilS. mentioned as an alternative you can move the downloaded file to a different location through your script.

查看更多
登录 后发表回答