How to end a session in Selenium and start a new one?

本秂侑毒 提交于 2021-02-11 18:23:18

问题


I'm trying to quit the browser session and start a new one when I hit an exception. Normally I wouldn't do this, but in this specific case it seems to make sense.

def get_info(url):
    browser.get(url)
    try:
        #get page data
        business_type_x = '//*[@id="page-desc"]/div[2]/div'
        business_type = browser.find_element_by_xpath(business_type_x).text
        print(business_type)
    except Exception as e:
        print(e)
        #new session
        browser.quit()
        return get_info(url)

This results in this error: http.client.RemoteDisconnected: Remote end closed connection without response

I expected it to open a new browser window with a new session. Any tips are appreciated. Thanks!


回答1:


You need to create the driver object again once you quite that. Initiate the driver in the get_info method again.

You can replace webdriver.Firefox() with whatever driver you are using.

def get_info(url):
    browser = webdriver.Firefox()
    browser.get(url)
    try:
        #get page data
        business_type_x = '//*[@id="page-desc"]/div[2]/div'
        business_type = browser.find_element_by_xpath(business_type_x).text
        print(business_type)
    except Exception as e:
        print(e)
        #new session
        browser.quit()
        return get_info(url)

You can also use close method instead of quit. So that you do not have to recreate the browser object.

def get_info(url):
    browser.get(url)
    try:
        #get page data
        business_type_x = '//*[@id="page-desc"]/div[2]/div'
        business_type = browser.find_element_by_xpath(business_type_x).text
        print(business_type)
    except Exception as e:
        print(e)
        #new session
        browser.close()
        return get_info(url)

difference between quit and close can be found in the documentation as well.

quit

close




回答2:


This error message...

http.client.RemoteDisconnected: Remote end closed connection without response

...implies that the WebDriver instance i.e. browser was unable to communicate with the Browsing Context i.e. the Web Browsing session.

If your usecase is to keep on trying to invoke the same url in a loop till the desired element is getting located you can use the following solution:

def get_info(url):
    while True:
        browser.get(url)
        try:
            #get page data
            business_type_x = '//*[@id="page-desc"]/div[2]/div'
            business_type = browser.find_element_by_xpath(business_type_x).text
            print(business_type)
            break
        except NoSuchElementException as e:
            print(e)
            continue


来源:https://stackoverflow.com/questions/60196372/how-to-end-a-session-in-selenium-and-start-a-new-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!