java+selenium如何定位一閃而退的彈窗且獲取該彈窗的文本
獲取頁面彈窗,首先要定位到相對應的元素,常見的是alert彈窗,這種是相對簡單的,切換到alert,並且返回當前打開的alert對象,使用switch_to.alert()方法定位到alert/confirm/prompt。然後使用text/accept/dismiss/send_keys按需進行操做:
alert = driver.switch_to_alert()
alert.accept() # 點擊確認按鈕
alert.dismiss() # 點擊取消按鈕
alert.text() # 返回alert/confirm/prompt中的文字信息
alert.send_keys(“hello”) # 向prompt中輸入文字
但是對於彈出提示彈窗後3秒就自動關閉的彈窗,一閃而過的彈窗就不是alert彈窗,自然也就不能用alert方法去獲取彈窗文本信息。
針對這種一閃而退的彈窗如何去定位元素?如何去獲取該彈窗的文本信息? 可以這樣去做:
如何定位一閃而退的彈窗元素?
當操作成功後,彈出該彈窗後,將鼠標懸停在彈窗上,然後再右鍵選擇檢查元素,即刻獲取該元素。將鼠標懸停在該種彈窗上,該彈窗就不會一閃而退,如果不將鼠標懸停在彈窗上而直接去定位該彈窗元素,過3秒該彈窗消失後,該元素也將消失。
如何獲取該彈窗的文本信息?
同上,先將鼠標懸停在該彈窗上,然後去定位元素,去該獲得該元素的文本信息。
該方法的腳本以java+selenium爲例,如下:
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import com.doctorsAdvice.UI.AutoLogger;
// 懸停到指定元素
public void hover(String xpath) {
try {
WebElement element = driver.findElement(By.xpath(xpath));
Actions act = new Actions(driver);
act.moveToElement(element).build().perform();
AutoLogger.log.info("懸停到指定元素");
} catch (Exception e) {
AutoLogger.log.error(e,e.fillInStackTrace());
AutoLogger.log.info("元素懸停失敗!");
}
}
//獲取閃退提示窗體信息,與期望文本信息作對比
public void alertText(String xpath, String target) {
hover(xpath);
try {
WebElement ele = driver.findElement(By.xpath(xpath));
String alerttext = ele.getText();
if( alerttext.contains(target) ) {
AutoLogger.log.info("測試成功!");
} else {
AutoLogger.log.info("測試失敗!");
}
} catch (Exception e) {
AutoLogger.log.info("未找到指定元素!!!");
System.out.print(e);
}
}
如何使用的是python+selenium的思路也是如此,先將鼠標懸停在該彈窗上,然後去定位元素,去該獲得該元素的文本信息。