简体   繁体   中英

Python Selenium Try-except Loop Connection error

there are multiple windows to get the info

I have a csv with keys to search in the first column, sometimes the website doesn't contain the element so I want driver quit then it can send the next key.

Here I give a specific example key I wanna search (and a normal situation):

    url = 'http://biz.finance.sina.com.cn/suggest/lookup_n.php?country=&q=21%BD%F0%BF%C602'
#   the following is a normal situation with all elements exist 
#   url = 'http://money.finance.sina.com.cn/bond/quotes/sz149373.html'
    driver.get(url)
    try:
        driver.switch_to.window(driver.window_handles[-1])
        driver.find_element_by_xpath('//div[@class="title tit06"]/a').click()       
        driver.switch_to.window(driver.window_handles[-1])
        driver.find_element_by_link_text('基本资料').click()
        driver.switch_to.window(driver.window_handles[-1])
        driver.find_element_by_link_text('发行信息').click()
    except:
        try:
            driver.switch_to.window(driver.window_handles[-1])
            driver.find_element_by_link_text('基本资料').click()
            driver.switch_to.window(driver.window_handles[-1])
            
            driver.find_element_by_link_text('发行信息').click()
        except:
            #error after quitting, cannot continue to search next key
            **driver.quit()**
        driver.switch_to.window(driver.window_handles[-1])
        driver.find_element_by_link_text('基本资料').click()
        driver.switch_to.window(driver.window_handles[-1])
        driver.find_element_by_link_text('发行信息').click()

ERROR:MaxRetryError: HTTPConnectionPool(host='127.0.0.1', port=63963): Max retries exceeded with url:

When the chrome quit in the highlighted line, then the error shows as above.

Many thanks!!

driver.quit() will shutdown all of driver operation in your computer. The error you receive mean it able to find your driver because it has been shutdown by your code. No further interaction can be execute.

If you want to close the current website, in your current window. Switch back to your parent window and using driver.close() instead (Remember to keep track of your parent window):

driver.switch_to.window(parent_window)
driver.close()

It only close the current window your driver is focusing on.Code example for your case:

for key in read_key_from_csv:
    # declare your driver inside loop
    driver = webdriver.Chrome()
    driver.get(key)
    # put all your code in side the loop
    # in case it not find element you want close the driver, the loop will jump to next key and start new driver
    driver.close()
    # no action relate to driver can perform after you close it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM