selenium的其他方法

本文详细介绍Selenium处理Cookie、页面等待、执行JS代码、切换窗口、操作iframe及处理弹窗的方法,涵盖登录QQ邮箱示例,适合自动化测试人员学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

selenium 处理cookie

driver.get_cookies()获取的是完整的cookie信息!不光有name、value,还有domain等其他信息!

# 把cookie转化为字典
cookies_dict = {cookie[‘name’]: cookie[‘value’] for cookie in driver.get_cookies()}

#删除一条cookie
driver.delete_cookie("CookieName")

# 删除所有的cookie
driver.delete_all_cookies()

页面等待

为什么需要等待

如果网站采用了动态html技术,那么页面上的部分元素出现时间便不能确定,这个时候就可以设置一个等待时间,强制要求在时间内出现,否则报错

页面等待的方法 time.sleep(10)

selenium执行js代码

import time
from selenium import webdriver

driver = webdriver.Chrome(executable_path='/home/worker/Desktop/driver/chromedriver')
driver.get("http://www.itcast.cn/")
time.sleep(1)

js = 'window.scrollTo(0,document.body.scrollHeight)' # js语句
driver.execute_script(js) # 执行js的方法

time.sleep(5)
driver.quit()

switch方法切换的操作

一个浏览器肯定会有很多窗口,所以我们肯定要有方法来实现窗口的切换。切换窗口的方法如下:

# 1. 获取当前所有的窗口
current_windows = driver.window_handles

# 2. 根据窗口索引进行切换
driver.switch_to.window(current_windows[1])

完整代码:

import time
from selenium import webdriver

driver = webdriver.Chrome(executable_path='/home/worker/Desktop/driver/chromedriver')
driver.get("https://www.baidu.com/")

time.sleep(1)
driver.find_element_by_id('kw').send_keys('python')
time.sleep(1)
driver.find_element_by_id('su').click()
time.sleep(1)

# 通过执行js来新开一个标签页
js = 'window.open("https://www.sogou.com");'
driver.execute_script(js)
time.sleep(1)

# 1. 获取当前所有的窗口
windows = driver.window_handles

time.sleep(2)
# 2. 根据窗口索引进行切换
driver.switch_to.window(windows[0])
time.sleep(2)
driver.switch_to.window(windows[1])

time.sleep(6)
driver.quit()

 iframe是html中常用的一种技术,即一个页面中嵌套了另一个网页,selenium默认是访问不了frame中的内容的,对应的解决思路是driver.switch_to.frame()

在使用selenium登录qq邮箱的过程中,我们会发现,无法在邮箱的登录input标签中输入内容,通过观察源码可以发现,form表单在一个frame中,所以需要切换到frame中

login_frame = driver.find_element_by_id('login_frame') # 定位frame元素
driver.switch_to.frame(login_frame) # 转向到该frame中

动手:模拟登陆qq邮箱

参考代码:

import time
from selenium import webdriver

driver = webdriver.Chrome(executable_path='/home/worker/Desktop/driver/chromedriver')

url = 'https://mail.qq.com/cgi-bin/loginpage'
driver.get(url)
time.sleep(2)

login_frame = driver.find_element_by_id('login_frame') # 根据id定位 frame元素
driver.switch_to.frame(login_frame) # 转向到该frame中

driver.find_element_by_xpath('//*[@id="u"]').send_keys('1596930226@qq.com')
time.sleep(2)

driver.find_element_by_xpath('//*[@id="p"]').send_keys('hahamimashicuode')
time.sleep(2)

driver.find_element_by_xpath('//*[@id="login_button"]').click()
time.sleep(2)

"""操作frame外边的元素需要切换出去"""
windows = driver.window_handles
driver.switch_to.window(windows[0])

content = driver.find_element_by_class_name('login_pictures_title').text
print(content)

driver.quit()

 当你触发了某个事件之后,页面出现了弹窗提示,处理这个提示或者获取提示信息方法如下:

driver.switch_to.alert() # 跟frame一样的处理方式!

页面前进和后退

driver.forward()     # 前进
driver.back()        # 后退

 selenium的优缺点

selenium能够执行页面上的js,对于js渲染的数据和模拟登陆处理起来非常容易

selenium由于在获取页面的过程中会发送很多请求,所以效率非常低,所以在很多时候需要酌情使用

### Selenium 中的不同等待方法 #### 隐式等待 隐式等待是指 WebDriver 借用了 Watir 的想法,在查找元素时,如果找不到该元素,则每隔一段时间重新尝试一次直到超过设定的时间限制[^1]。一旦设置了隐式的超时时间,它将在 WebDriver 实例的整个生命周期内生效。当页面加载较慢或者网络状况不佳的时候,这有助于防止立即失败并允许有更多的时间去定位目标元素。 对于隐式等待而言,只要在初始化浏览器驱动程序后配置一次即可: ```java driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); ``` 这段代码表示给定的最大时间为 10 秒钟用于寻找任何新出现的 web 元素;若在此期间仍未发现所需元素则触发 `NoSuchElementException` 异常[^4]。 #### 显式等待 不同于全局性的隐式等待机制,显式等待仅针对单个操作有效,并且可以根据具体条件灵活调整。通过结合使用 `WebDriverWait` 和 `ExpectedConditions` 类能够实现更加精准控制的行为模式——即只会在满足某些预期状态(比如某个按钮变得可点击或是某段文字出现在 DOM 结构里)才继续向下执行后续逻辑[^2]。 下面是一个简单的例子展示了如何利用显式等待来处理一个需要等到变为可见并且可以被点击的按钮: ```java // 导入必要的包 import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class ExplicitWaitExample { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30)); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("myDynamicButton"))); // 执行其他动作... } finally { driver.quit(); } } } ``` 在这个案例中,我们指定了最长等待时间为三十秒 (`Duration.ofSeconds(30)`), 并且只有当 ID 为 `"myDynamicButton"` 的 HTML 元素既显示出来又处于可用状态才会结束阻塞流程向前推进下去. #### FluentWait (流畅等待) 除了上述两种基本形式外,Selenium 还提供了另一种更为高级的选择叫做 **FluentWait**, 它允许开发者自定义轮询频率以及忽略特定类型的异常从而达到更细粒度级别的定制化需求。相比于普通的显式等待来说,FulentWait 提供了更大的灵活性因为它不仅限于固定间隔检查而是支持连续不断地监测直至成功匹配到期望的结果为止. 这里有一个采用 FluentWait 来代替传统方式的例子: ```java // 导入必要的包 import java.time.Duration; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; public class FluentWaitExample { private static final int TIMEOUT_IN_SECONDS = 30; private static final long POLLING_INTERVAL_MILLIS = 500L; public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); Wait<WebDriver> fluentWait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(TIMEOUT_IN_SECONDS)) .pollingEvery(Duration.ofMillis(POLLING_INTERVAL_MILLIS)) .ignoring(NoSuchElementException.class) .ignoring(StaleElementReferenceException.class); WebElement dynamicElement = fluentWait.until(drv -> drv.findElement(By.id("dynamicID"))); // 继续进行下一步骤... driver.quit(); } } ``` 此片段创建了一个名为 `fluentWait` 的对象实例,其最大超时期望值设为了三秒钟(`TIMEOUT_IN_SECONDS`) ,每次查询之间的休眠周期大约半秒(`POLLING_INTERVAL_MILLIS`). 同样地,这里也列举了一些可能发生的错误情形以便它们不会中断正常的自动化进程[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值