如何使用selenium在网页上点击广告等动态链接

问题描述 投票:1回答:1

我是Selenium webdriver的新手,并试图测试一个有动态链接(动态广告)的网页。示例:https://mail.rediff.com/cgi-bin/login.cgi上的广告

我尝试使用xpath,classname和id但这些都没有工作。它正在发生,因为每次在页面上显示新内容,所以它无法找到元素并在线程“main”中抛出异常:

org.openqa.selenium.NoSuchElementException: Unable to locate element: #map.

我的代码是:

package Selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Image_Link {

    static WebDriver driver ;
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub


        //System.setProperty("webdriver.chrome.driver", "E://chromedriver_win32//chromedriver.exe");
        //driver = new ChromeDriver();
        System.setProperty("webdriver.gecko.driver", "E://geckodriver-v0.21.0-win64//geckodriver.exe");
        driver = new FirefoxDriver();
        Actions actions = new Actions(driver);
        driver.get("https://mail.rediff.com/cgi-bin/login.cgi");
        //WebElement Dynamic_ads=driver.findElement(By.className("rhs-area floatR"));
        WebElement Dynamic_ads=driver.findElement(By.id("map"));
        actions.moveToElement(Dynamic_ads).perform();
        WebElement ad_Link = driver.findElement(By.cssSelector("#map > area:nth-child(2)"));
        actions.moveToElement(ad_Link);
        actions.click();
        actions.perform();

        //driver.navigate().to("www.google.com");

        //String value = driver.findElement(By.id("hplogo")).getAttribute("title");


    }

}
selenium-webdriver
1个回答
0
投票

无法找到动态广告的元素,因为它尚未在加载页面上完全加载。我建议为您正在寻找的特定添加添加明确的等待时间。你可以在这里查看这个link了解更多信息。

无论如何,这是你的解决方案:

1.)实现WebDriverWait:WebDriverWait wait = new WebDriverWait(driver, 20);

2.)将你的Dynamic_ads数据更改为wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("map")));然后再做Dynamic_ads.click();

要么

2.)将你的Dynamic_ads数据更改为wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//map[@id='map']/*")));然后再做Dynamic_ads.click();。注意:这将选择第一个子节点。

© www.soinside.com 2019 - 2024. All rights reserved.