selenium之調用js解決淘寶點擊下一頁問題(JAVA版)


最近研究點擊淘寶商品底部 點擊“下一頁”問題。今天經網友指導得解,感謝網友且聽風吟和燊!

分析原因:沒加載上和定位問題

解決思路:用js將瀏覽器滾動到底部,等待加載完,再進行點擊

解決代碼

package wxLinkParaser;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class click {
    public boolean click(){
        System.getProperties().setProperty("webdriver.chrome.driver", "C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe");
        WebDriver webDriver = new ChromeDriver();
       
        try{
            webDriver.get("http://list.taobao.com/itemlist/default.htm?cat=50000671&viewIndex=1&as=0&atype=b&style=grid&same_info=1&isnew=2&tid=0&_input_charset=utf-8");
            try{
                Thread.sleep(5000); // 等待瀏覽器加載
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            webDriver.manage().window().maximize(); // 使瀏覽器窗口最大化

            //js代碼
            String js1 = "return document.documentElement.scrollHeight;";  // 滑動條的位置值
            String js2 = "scroll(0,10000);";
            
            ((JavascriptExecutor)webDriver).executeScript(js2);//執行js代碼,返回瀏覽器滾動高度
            try{
                Thread.sleep(3000); //等待瀏覽器加載
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ((JavascriptExecutor)webDriver).executeScript(js1);//執行js代碼,滾動10000像素
            
            
            try{
                Thread.sleep(3000); // wait for web loading
            } catch (InterruptedException e) {
                e.printStackTrace();
            }  
            
             WebElement Whref = webDriver.findElement(By.cssSelector("a.J_Ajax.btn.next"));//得到要點擊的“下一頁”鏈接
            
             Whref.click();//進行點擊
             //webDriver.close();這句先注視掉,以便觀察結果
             return true;
        }catch(org.openqa.selenium.NoSuchElementException ex){
            System.out.println("找不到要的下一頁鏈接!");
            //webDriver.close();這句先注視掉,以便觀察結果
            return false;
        }            
        
    }
        
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        click c = new click();
        if(c.click()){
            System.out.println("點擊成功!");
        }
    }

}

 

 

 

 


免責聲明!

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



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