2012-02-13 68 views
1

我怎樣才能得到一個網頁的所有鏈接,並使用硒我怎樣才能得到一個網頁的所有鏈接,並使用硒

//代碼

WebDriver driver = new FirefoxDriver(); 
    driver.get("http://www.HRS.com"); 
    List<WebElement> MyList = driver.findElements(By.xpath("//a")); 
    for(WebElement Element : MyList) 
    { 
    Element.click(); ----> m getting an error (IN 2 ITERATION) stating 
          "Element not found in the cache - perhaps the page has 
          changed since it was looked up" 

    } 
點擊逐個點擊逐個

任何人都可以幫我嗎?

在此先感謝

+0

我現在面臨使用PHPUnit +硒類似的問題。 getXpathCount('// a')返回25.但是,isElementPresent('// a [3]')向前返回false。 – 2012-02-27 13:37:08

回答

0

當你點擊鏈接你是以下的鏈接,你已經找到的元素無效。你需要要麼回到頁面:

driver.navigate().back(); 

做這樣後,你將需要刷新列表中的元素,這意味着當前的循環結構可能會無法正常工作。

另一種選擇是通過以下方式查詢:

//Might need to do some extra work if this is a relative link 
HttpURLConnection httpConn = new HttpURLConnection(element.getAttribute("href")); 
URLConnection = httpConn.openConnection(); 
if (conn instanceof HttpURLConnection) { 
    HttpURLConnection http = (HttpURLConnection) conn; 
    Assert.assertTrue("Invalid link on page.", http.getResponseCode() < 400); 
} 
0

其中最繁瑣的任務,IMO,對於測試工程師,手動驗證鏈接。我們可以實現大部分流程的自動化,只要我們有URL,點擊鏈接後我們可以預期到哪裏,我們可以使用Selenium和一點JS來驗證這個功能。

在下面的示例中,我們首先導航到我們想要的網站,然後使用Selenium的getEval()函數來執行JavaScript,該頁面收集頁面上的所有鏈接(錨點)並將它們保存在逗號分隔的列表中。這個列表然後被分割並推入到一個數組中。然後,我們遍歷數組中的鏈接列表,單擊每個鏈接,然後使用go_back導航回起始頁面。下面

例子:

use strict; 
use warnings; 
use Time::HiRes qw(sleep); 
use Test::WWW::Selenium; 
use Test::More "no_plan"; 

my $sel = Test::WWW::Selenium->new(host => "localhost", 
            port => 4444, 
            browser => "*iexplore", 
            browser_url => "http://www.google.com/"); 

$sel->open_ok("/", "true"); 

$sel->set_speed("1000"); 

my $javascript = "var allLinks = this.browserbot.getCurrentWindow().document.getElementsByTagName('a'); 
       var separator = ','; 
       var all_links_texts = ''; 

       for(var i = 0; i < allLinks.length; i++) { 
         all_links_texts = all_links_texts+separator+allLinks[i].href; 
       } 
       all_links_texts;"; 

# Get all of the links in the page and, using a comma to separate each one, add them to the all_links_texts var. 
my $link_list = $sel->get_eval($javascript); 

my @link_array = split /,/ , $link_list; 

my $count = 0; 

# Click on each link contained in the array and then go_back 
# You can add other logic here like capture and store a screenshot for example 
foreach my $link_name (@link_array) { 

    unless ($link_name =~ /^$/){ 

     $sel->click_ok("css=a[href $= $link_name]"); 

     $sel->wait_for_page_to_load("30000"); 

     print "Clicked Link href: $link_name \n"; 

     $sel->go_back(); 

     $count++; 
    } 
} 
print "Clicked $count URL's"; 
pass; 

以上可以很容易地修改做的不僅僅是點擊鏈接等等。當然,在所點擊的鏈接的預定着陸頁上,沒有什麼能夠勝出。

我們充分的博客文章是在這裏:Get all links and click on each one

相關問題