org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element


org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element(識別不到想要的元素)

想獲取到收件箱中包含堅果雲的字段

 

 此處遇見的問題,網頁中想要識別的元素在iframe框中,於是不能直接:

driver.findElement(By.id("img_out_995536807")).click();
需要先識別frame,然后再找元素:
 driver.switchTo().frame("login_frame").findElement(By.id("img_out_995536807")).click();
package com.xp.climb.selenium;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class LoginRenren {

    public static void main(String[] args) throws IOException, InterruptedException {
        //geckodriver配置
        System.setProperty("webdriver.chrome.driver", "E:\\selenium\\chromedriver.exe");
        //聲明使用的是谷歌瀏覽器
        ChromeDriver driver = new ChromeDriver();
        //使用谷歌瀏覽器打開QQ郵箱網頁
        driver.get("https://mail.qq.com/");
        //元素定位,提交用戶名以及密碼

        driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
        driver.switchTo().frame("login_frame").findElement(By.id("img_out_995536807")).click();
//        driver.findElementByName("u").clear();  //清空后輸入
//        driver.findElementByName("u").sendKeys("11");
//        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//        driver.findElementById("p").clear(); //清空后輸入
//        driver.findElementById("p").sendKeys("11");
//        //元素定位,點擊登陸按鈕
//        driver.findElementById("login_button").click();
        Thread.sleep(10*1000);  //休息一段時間,使得網頁充分加載。注意這里非常有必要
        Set<Cookie> cookies = driver.manage().getCookies();
        //獲取登陸的cookies
        String cookieStr = "";
        for (Cookie cookie : cookies) {
            cookieStr += cookie.getName() + "=" + cookie.getValue() + "; ";
        }
        System.out.println(cookieStr);
        //基於Jsoup,使用cookies請求個人信息頁面
        Response orderResp = Jsoup   //添加一些header信息
                .connect("https://mail.qq.com/cgi-bin/frame_html?sid=P5g0fdIbJnC1THcX&r=3955f00b3eaae54686461e267bbfc07f")
//                .header("Host", "www.renren.com")
                .header("Connection", "keep-alive")
                .header("Cache-Control", "max-age=0")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8")
//                .header("Origin", "http://www.renren.com")
                .header("Referer", "https://mail.qq.com/")
                .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Accept-Encoding", "gzip, deflate, br")
                .header("Upgrade-Insecure-Requests", "1")
                .cookie("Cookie", cookieStr)
                .execute();
        //解析數據
        Document doc = orderResp.parse();
        System.out.println(doc);
        org.jsoup.select.Elements elements = doc.select("td[class=gt]")
                .select("div[class=tf no]");
        for (Element element : elements) {
            if (element.text().contains("堅果雲")) {
                System.out.println(element.text());
            }
        }
        driver.quit();  // 關閉瀏覽器
    }
}

 

總結:

selenium webdriver定位不到元素的五種原因及解決辦法 

1.動態id定位不到元素

  for example:

  //WebElement xiexin_element = driver.findElement(By.id("_mail_component_82_82"));

  WebElement xiexin_element = driver.findElement(By.xpath("//span[contains(.,'寫 信')]"));

  xiexin_element.click();

  上面一段代碼注釋掉的部分為通過id定位element的,但是此id“_mail_component_82_82”后面的數字會隨着你每次登陸而變化,此時就無法通過id准確定位到element。

  所以推薦使用xpath的相對路徑方法查找到該元素。
 

 2.iframe原因定位不到元素

  由於需要定位的元素在某一個frame里邊,所以有時通過單獨的id/name/xpath還是定位不到此元素

  比如以下一段xml源文件:

<iframe id="left_frame" scrolling="auto" frameborder="0" src="index.php?m=Index&a=Menu" name="left_frame" noresize="noresize" style="height: 100%;visibility: inherit; width: 100%;z-index: 1">

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<body class="menuBg">

<div id="menu_node_type_0">

<table width="193" cellspacing="0" cellpadding="0" border="0">

<tbody>

<tr>

<tr>

<td id="c_1">

<table class="menuSub" cellspacing="0" cellpadding="0" border="0" align="center">

<tbody>

<tr class="sub_menu">

<td>

<a href="index.php?m=Coupon&a=SearchCouponInfo" target="right_frame">密碼重置</a>

</td>

</tr>

  原本可以通過

  WebElement element = driver.findElement(By.linkText("密碼重置"));

  來定位此元素,但是由於該元素在iframe id="left_frame"這個frame里邊 所以需要先通過定位frame然后再定位frame里邊的某一個元素的方法定位此元素

  WebElement element =driver.switchTo().frame("left_frame").findElement(By.linkText("密碼重置"));

  3.不在同一個frame里邊查找元素

  大家可能會遇到頁面左邊一欄屬於left_frame,右側屬於right_frame的情況,此時如果當前處在

  left_frame,就無法通過id定位到right_frame的元素。此時需要通過以下語句切換到默認的content

  driver.switchTo().defaultContent();

  例如當前所在的frame為left_frame

  WebElement xiaoshoumingxi_element = driver.switchTo().frame("left_frame").findElement(By.linkText("銷售明細"));

  xiaoshoumingxi_element.click();

  需要切換到right_frame

  driver.switchTo().defaultContent();

  Select quanzhong_select2 = new Select(driver.switchTo().frame("right_frame").findElement(By.id("coupon_type_str")));

  quanzhong_select2.selectByVisibleText("售后0小時");

  4. xpath描述錯誤

  這個是因為在描述路徑的時候沒有按照xpath的規則來寫 造成找不到元素的情況出現

  5.點擊速度過快 頁面沒有加載出來就需要點擊頁面上的元素

  這個需要增加一定等待時間,顯示等待時間可以通過WebDriverWait 和util來實現

  例如:

  //用WebDriverWait和until實現顯示等待 等待歡迎頁的圖片出現再進行其他操作

  WebDriverWait wait = (new WebDriverWait(driver,10));

  wait.until(new ExpectedCondition<Boolean>(){
  public Boolean apply(WebDriver d){
  boolean loadcomplete = d.switchTo().frame("right_frame").findElement(By.xpath("//center/div[@class='welco']/img")).isDisplayed();

  return loadcomplete;

  }

  });

  也可以自己預估時間通過Thread.sleep(5000);//等待5秒 這個是強制線程休息

  6.firefox安全性強,不允許跨域調用出現報錯

  錯誤描述:uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMNSHTMLDocument.execCommand]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location:

  解決辦法:

  這是因為firefox安全性強,不允許跨域調用。

  Firefox 要取消XMLHttpRequest的跨域限制的話,第一

  是從 about:config 里設置 signed.applets.codebase_principal_support = true; (地址欄輸入about:config 即可進行firefox設置)

  第二就是在open的代碼函數前加入類似如下的代碼: try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } catch (e) { alert("Permission UniversalBrowserRead denied."); }

  最后看了乙醇的文章

import java.io.File;

importorg.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.chrome.ChromeDriver;

importorg.openqa.selenium.support.ui.ExpectedCondition;

importorg.openqa.selenium.support.ui.WebDriverWait;

public classButtonDropdown {
public static voidmain(String[] args) throws InterruptedException {
WebDriver dr = newChromeDriver();

File file = newFile("src/button_dropdown.html");

String filePath = "file:///" + file.getAbsolutePath();

System.out.printf("nowaccesss %s \n", filePath);

dr.get(filePath);

Thread.sleep(1000);

// 定位text是watir-webdriver的下拉菜單

// 首先顯示下拉菜單

dr.findElement(By.linkText("Info")).click();

(newWebDriverWait(dr, 10)).until(new ExpectedCondition<Boolean>(){
public Booleanapply(WebDriver d){
returnd.findElement(By.className("dropdown-menu")).isDisplayed();

}

});

// 通過ul再層級定位

dr.findElement(By.className("dropdown-menu")).findElement(By.linkText("watir-webdriver")).click();

Thread.sleep(1000);

System.out.println("browser will be close");

dr.quit();

}

}

  然后我自己定位的。

public XiaoyuanactivityPage zipaixiuye(){
driver.navigate().refresh();

luntan.click();

WebDriverWrapper.waitPageLoad(driver,3);

(new WebDriverWait(driver, 10)).until(newExpectedCondition<Boolean>() {
public Boolean apply(WebDriverdriver){
returndriver.findElement(By.className("TFB_sub_li")).isDisplayed();

}

});

driver.findElement(By.className("TFB_sub_li")).findElement(By.linkText("自拍秀")).click();

returnPageFactory.initElements(this.getDriver(),

XiaoyuanactivityPage.class);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM