selenium - Selenium 点击功能键
问题描述
我还是 Selenium 测试世界的新手,我目前正在使用 Selenium ChromeDriver 进行测试。
这是我想要完成的,但没有成功:
1 - 我在 Chrome 中打开了大约 50 个标签页,我想一次按 F9 键
2 - 对所有选项卡按 F9 后,如果页面上出现某些文本(无结果),则关闭选项卡。
我希望有人可以在这两个功能中的任何一个方面提供帮助。
提前致谢。
解决方案
没有办法(我知道)一次将按键发送到多个窗口句柄(每个选项卡在 Selenium 中称为窗口句柄),但是您可以循环浏览窗口并尝试使用某个Actions
类来发送 F9 键按到每一页,然后检查您想要的文本。
您将需要利用Driver.WindowHandles
来获取当前打开的选项卡列表,并Driver.SwitchTo().Window()
更改选项卡之间的焦点。Actions
类可以模拟发送 F9 键到当前窗口。Driver.Close()
将关闭现有选项卡。
最后,WebDriverWait
将用于在代码评估是否应关闭当前选项卡之前等待填充“无结果”文本。如果所需的元素在指定的时间参数内未出现在页面上,WebDriverWait
将抛出 a ,因此我们包装在/块中以处理“无结果”既存在又不存在的情况。TimeoutException
WebDriverWait
try
catch
C# 中的以下代码示例应该可以帮助您入门:
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
// given you have 50 tabs open already
// get window handles -- this is a List<string> with length 50, one for each tab
var handles = Driver.WindowHandles;
// iterate window handles, switch to the window, and send F9 key
foreach (var window in handles)
{
// switch to the window
Driver.SwitchTo().Window(window);
// send F9 key press to the current tab
new Actions(Driver).SendKeys(Keys.F9).Perform();
// wait for 'No Results' text
try
{
new WebDriverWait(Driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[contains(text(), 'No Results')]")));
// if TimeoutException is not thrown, then No Results text exists. so close the tab
Driver.Close();
}
catch (TimeoutException)
{
// case: 'No Results' text does not exist. do not close the tab.
}
}
这是一个非常笼统的大纲,几乎可以肯定,您需要进行一些修改才能使其完全正常工作。例如,new WebDriverWait(Driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[contains(text(), 'No Results')]")));
可能需要调整其中使用的 XPath,以确保找到显示“无结果”文本的正确元素。希望这能让你开始。
推荐阅读
- angular-forms - 如何以角度形式实现速记验证?
- python - Django Rest Framework - 如何对 MSSQL 存储过程中的数据进行建模和序列化
- python - Django 无法读取其他应用程序的模型
- python - 使用 Python 和 Selenium 将 APK 上传到解释为 URL 的网页
- arrays - 在 bash 中对带有空格的数组进行切片
- imagemagick - 在 ImageMagick 的循环中使用复合
- javascript - navigator.mediaDevices.enumerateDevices() 返回空标签
- scroll - 滚动条的粘性褪色画廊
- git - 无法在控制台中输入 github 的密码
- cassandra - Cassandra 计数有限制