Selenium 4 - Control browser history

Controlling browser history (back and forward) is an important task in automated testing. Selenium 4 provides simple yet powerful ways to simulate user navigation behavior in a browser. This tutorial will show you how to go back and forward in browser history using Selenium 4.

In order to better demonstrate the forward and backward operations, we can first visit a website with multiple links, such as the rookie tutorial.

You can click on one of the titles at will, and then perform forward and backward operations. This more clearly demonstrates Selenium 4's ability to control browser history.

example

from selenium import webdriver  # 导入Selenium模块用于控制浏览器
from selenium.webdriver.common.by import By  # 导入By类定义了用于查找元素的方法
from selenium.webdriver.support.ui import WebDriverWait  # 导入WebDriverWait类用于等待页面加载完成
from selenium.webdriver.support import expected_conditions as EC  # 导入expected_conditions模块定义了一些常用条件
from time import sleep  # 导入sleep函数用于延时操作

driver = webdriver.Chrome()  # 创建Chrome浏览器驱动实例

url = 'https://www.runoob.com/'  # 要访问的URL
driver.get(url)  # 打开浏览器并访问URL

title_link = driver.find_element(By.XPATH, "//h4[text()='【学习 HTML】']")  # 查找标题元素
title_link.click()  # 点击标题

wait = WebDriverWait(driver, 10)  # 设置等待时间为10秒
wait.until(EC.title_contains("HTML 教程"))  # 等待页面标题包含"HTML 教程"

driver.back()  # 后退操作
sleep(3)  # 停顿三秒

driver.forward()  # 前进操作
sleep(5)  # 停顿五秒

driver.quit()  # 关闭浏览器

Guess you like

Origin blog.csdn.net/m0_67268191/article/details/132172668