package Selenium.Locators;
import java.util.List;
import java.net.URL;
import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.firefox.FirefoxDriver;
import sun.net.www.protocol.http.HttpURLConnection;
public class program {
// to get all the links in a website which has anchor tag and img tag
public static List findAllLinks(WebDriver driver)
{
List elementList = new ArrayList();
elementList = driver.findElements(By.tagName("a"));
elementList.addAll(driver.findElements(By.tagName("img")));// to get the anchor tag and img tag values
List finalList = new ArrayList();
for (WebElement element : elementList)//it shows error in this line
{
if(element.getAttribute("href") != null)
{
finalList.add(element);
}
}
return finalList;
}
// to find all the broken links in a website
public static String isLinkBroken(URL url) throws Exception
{
url = new URL("https://www.yahoo.com/");// to find the broken links
String response = ""
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try
{
connection.connect();
response = connection.getResponseMessage();
connection.disconnect();
return response;
}
catch(Exception exp)
{
return exp.getMessage();
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver", "G:\\AllLinks\\src\\test\\java\\Selenium\\Locators\\geckodriver.exe");
FirefoxDriver ff = new FirefoxDriver();
ff.get("https://www.yahoo.com/");
List allImages = findAllLinks(ff);
System.out.println("Total number of elements found " + allImages.size());
for (WebElement element : allImages)// It shows the error in this line
try
{
System.out.println("URL: " + element.getAttribute("href")+ " returned " + isLinkBroken(new URL(element.getAttribute("href"))));
//System.out.println("URL: " + element.getAttribute("outerhtml")+ " returned " + isLinkBroken(new URL(element.getAttribute("href"))));
}
catch(Exception exp)
{
System.out.println("At " + element.getAttribute("innerHTML") + " Exception occured -> " + exp.getMessage());
}
}
}
如果我運行代碼,我得到以下錯誤消息錯誤:(69,35)java:incompatible types:java。 lang.Object無法轉換爲org.openqa.selenium.WebElement 此代碼用於獲取網站中的所有鏈接,以便我們可以手動對其進行測試以查找所有元素。不兼容的類型:java.lang.Object不能轉換爲org.openqa.selenium.WebElement
不是一個解決辦法,但你應該使用列表 –
@ShekharSwami幾秒打我:d它可能是一個解決方案,但因爲我認爲列表或多或少列表