简体   繁体   中英

python selenium open link in new tab and continue session in new tab

i lost my current session when selenium click the link and new tab open.i don't know how to continue session in new tab in yahoo.com.

driver.get("https://in.yahoo.com")
search_field = driver.find_element_by_id('header-search-input')
search_field.clear()
search_field.send_keys('guru99')
search_field.submit()
elements =driver.find_element_by_xpath('//a[contains(@href, "https://www.guru99.com")]')
elements.click()
driver.find_element_by_link_text("What is Python?")
time.sleep(20)
driver.close()

You can open search result in the same tab:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://in.yahoo.com")
search_field = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, 'header-search-input')))
search_field.clear()
search_field.send_keys('guru99')
search_field.submit()
el = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//a[contains(@href, "https://www.guru99.com")]')))
url = el.get_attribute('href')
driver.get(url)
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@title="Python"]'))).click()
driver.close()

You need to use driver.switch to the window. Then going back.

window_before = driver.window_handles[len(driver.window_handles)]
driver.switch_to.window(len(driver.window_handles))
#do stuff
driver.switch_to.window(window_before)

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