Utkarsh Agrawal
Utkarsh Agrawal

Reputation: 19

How to take multiple screenshots through Selenium in Python?

GECKODRIVER_PATH = 'F:/geckodriver.exe' 

firefox_options = Options()  
firefox_options .add_argument("-headless")  
driver = webdriver.Firefox(executable_path=CHROMEDRIVER_PATH, firefox_options = firefox_options )  

test = []
test.append('http://google.com')
test.append('http://stackoverflow.com')

for x in test:
    print x
    driver.get(x)
    driver.set_page_load_timeout(20)
    filename = str(x)+'.png'
    driver.save_screenshot( filename )
    driver.close()

Now, how can I take multiple screenshots and save them in the different filename? As you can see I am trying to save the filename according to domain URL but failed.

See the error below:

http://google.com
http://card.com
Traceback (most recent call last):
  File "F:\AutoRecon-master\test.py", line 125, in <module>
    driver.get(x)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 326, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 314, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: Tried to run command without establishing a connection

Can anyone please tell me what is the exact problem is? Will be a big help.

Upvotes: 0

Views: 2188

Answers (2)

Corey Goldberg
Corey Goldberg

Reputation: 60604

Tried to run command without establishing a connection

you are closing the browser within your for loop... so the 2nd time through the loop it fails with the error above (since the browser is closed, the connection to geckodriver has already been terminated).

other issues:

  • you are setting the page_load_timeout after you have already fetched the page, so it is not doing anything useful.
  • using CHROMEDRIVER_PATH as the name for Geckodriver is just confusing. Chromedriver is not used at all here.

Upvotes: 2

Andersson
Andersson

Reputation: 52665

Try to move driver.close() out of loop:

for x in test:
    print x
    driver.get(x)
    driver.set_page_load_timeout(20)
    filename = str(x)+'.png'
    driver.save_screenshot( filename )
driver.close()

Also note that x is already a string, so there is no need in str(x)

P.S. I'm not sure that http://stackoverflow.com.png filename is acceptable, you might need to use:

filename = x.split('//')[-1] + '.png'

Upvotes: 2

Related Questions