0

Type mismatch: cannot convert from WebElement to WebDriver

Getting this error in my code why?

package testcases;

import java.util.List;

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

import io.github.bonigarcia.wdm.WebDriverManager;

public class WebDriver_vs_WebElement {

    public static void main(String[] args) 
    {
        WebDriver driver;
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
        WebElement dropdown = driver.findElement(By.id("searchLanguage"));
        
        WebDriver block = driver.findElement(By.xpath("//*[@id=\"www-wikipedia-org\"]/div[11]/div[3]"));
        List<WebElement> links = block.findElements(By.tagName("a"));
        System.out.println("Total links in particular block: " +links.size());
        for(WebElement link:links)
        {
            System.out.println(link.getText() + "---URL : " +link.getAttribute("href"));
        }
        
    }

}
1
  • What line of code is the offender?
    – kirbycope
    Jan 11, 2022 at 3:50

1 Answer 1

2
WebDriver block = driver.findElement(By.xpath("//*[@id=\"www-wikipedia-org\"]/div[11]/div[3]"));

A WebDriver is not an WebElement; objects of these types are in different objects hierarchies.

enter image description here

https://www.javadoc.io/doc/org.seleniumhq.selenium/selenium-api/2.50.1/org/openqa/selenium/WebDriver.html

enter image description here

https://www.javadoc.io/static/org.seleniumhq.selenium/selenium-api/2.50.1/org/openqa/selenium/WebElement.html

Thus you need a WebElement variable to hold a WebElement object:

WebElement block = driver.findElement(By.xpath("//*[@id=\"www-wikipedia-org\"]/div[11]/div[3]"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.