Selenium.Common.Exceptions.Webdriverexception: Message: Invalid Session Id Using Selenium with Chromedriver and Chrome Through Python

Python Selenium Error: invalid session id

You are getting that error because you called driver.close() before calling driver.implicitly_wait(5). You cannot close the last/only browser window and then use commands with the driver. Either don't close the browser window, or open up a new window first.

To open up a new browser window, use:

driver.execute_script("window.open('');")

getting error selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id while crawling links of a table

You are the closing browser before taking page_source value so selenium unable to get the session.Try now.

from bs4 import BeautifulSoup
from selenium import webdriver

url="https://www.zaubacorp.com/company-list"
driver = webdriver.Chrome(r'C:\chromedriver.exe')
driver.get(url)
soup = BeautifulSoup(driver.page_source,'html.parser')
driver.close()
table = soup.find('table',{'id':'table'})
body = table.find('tbody')
for links in body.find_all('a'):
print(links['href'])

InvalidSessionIdException while Selenium driver is not closed

You are missing a break statement in the for, without it the code behaves as the loop wasn't successful and executes the else block where you close the driver for a second time. See Why does python use 'else' after for and while loops? for more detailed explanation.

Adding break statement at the end of the try block should solve the issue.

InvalidSessionIdException: Message: invalid session id taking screenshots in a loop using Selenium and Python

It doesn't looks like there is any dependency on the Copyright.

To save_screenshot() you can open the image url in the adjascent tab and use the following Locator Strategies:

  • Code Block:

    for i in range(2):
    driver.get("https://apod.nasa.gov/apod/random_apod.html")
    windows_before = driver.current_window_handle
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src^='https://apod.nasa.gov/apod']")))
    imageLink = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h1[normalize-space()='Astronomy Picture of the Day']//following::p[2]//a/img"))).get_attribute("src")
    driver.execute_script("window.open('" + imageLink +"');")
    windows_after = driver.window_handles
    new_window = [x for x in windows_after if x != windows_before][0]
    driver.switch_to.window(new_window)
    driver.save_screenshot(f"image_{str(i)}.png")
    driver.close()
    driver.switch_to.window(windows_before)
    driver.quit()
  • Screenshot:

    • image_0
      image_0

    • image_1
      image_1



Related Topics



Leave a reply



Submit