Article directory
- foreword
- 1. Scene
- 2. Design
-
- 1. Import library
- 2. Start the browser instance
- 3. Visit the homepage of Station C
- 4. Set implicit wait
- 5. Enter selenium in the toolbar search box
- 6. Click the search button
- 7. Get all window handles
- 8. Switch window handle
- 9. Click on the first resource title
- 10. Get all window handles
- 11. Close the search result page window ①
- 12. Close the blog details page window②
- 13. Close the home page window of Station C③
- 14. End the webdriver process
- Summarize
foreword
Hello everyone, I am Kongkong star. In this article, I will share with you the closing of the specified window in the basics of Selenium.
The selenium version used in this article is as follows:
Version: 4.8.2
The browsers used in this article are as follows:
1. Scene
Visit the homepage of station C, enter selenium in the toolbar search box, and click the search button;
on the search result page, click the title of the first selenium resource;
first close the search result page window①;
then close the blog detail page window②;
finally close the homepage of station C window③.
2. Design
1. Import library
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
2. Start the browser instance
driver = webdriver.Chrome()
3. Visit the homepage of Station C
driver.get('https://www.csdn.net/')
4. Set implicit wait
driver.implicitly_wait(5)
5. Enter selenium in the toolbar search box
driver.find_element(By.ID, 'toolbar-search-input').send_keys('selenium')
6. Click the search button
driver.find_element(By.ID, 'toolbar-search-button').click()
7. Get all window handles
win = driver.window_handles
8. Switch window handle
driver.switch_to.window(win[-1])
9. Click on the first resource title
driver.find_element(By.CLASS_NAME,'item-hd').click()
10. Get all window handles
win = driver.window_handles
print(win)
['D2A3C0BCAA4F5F8F1812491BFCC5E4B5', 'FC5E02CA1A6AE8A131BE2F0E9A4340E4', '02367B50072F97AEFE8014CD063A5AFE']
11. Close the search result page window ①
Because the current window handle is still on the search result page, it is closed directly without switching the window handle
driver.close()
12. Close the blog details page window②
driver.switch_to.window(win[2])
print(driver.title)
driver.close()
selenium用法详解【从入门到实战】【Python爬虫】【4万字】_Dream丶Killer的博客-CSDN博客
13. Close the home page window of Station C③
# 强制等待3秒,为了观察效果
sleep(3)
driver.switch_to.window(win[0])
print(driver.title)
driver.close()
CSDN - 专业开发者社区
14. End the webdriver process
driver.quit()