//这是我得到的异常
线程“main”中出现异常java.lang.ClassCastException:无法将类转换为类java.net. HttpURLConnection(类和java.net.HttpURLConnection位于加载程序“引导”模块java.base中)
// this is what I tried
package brokenLinks;
import java.io.IOException;
import java.net.HttpURLConnection;
//import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
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 ValidateBrokenLinksTest {
public static void main(String[] args) throws IOException {
//set up the webdriver driver
WebDriverManager.chromedriver().setup();
//launch chrome driver
WebDriver driver = new ChromeDriver();
//maximize the window
driver.manage().window().maximize();
//load the url
driver.get("https://testerscafe.in/");
//implicit wait for page to load
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
//get all the links in the webpage using tagName called "a" and store them inside list collection
List<WebElement> elements = driver.findElements(By.tagName("a"));
//get the total number of links available
int size = elements.size();
System.out.println("Number of links available in the webpage :"+size);
//iterate from each link and get the attribute value of each link
for(WebElement links : elements) {
String link = links.getAttribute("href");
//load all the links to URL class
URL url = new URL(link);
//set up the connection
HttpURLConnection connection = (HttpURLConnection)(url.openConnection());
connection.connect();
//validatation
if(connection.getResponseCode()>=400) {
System.out.println(link+" ==> is a broken link");
}
else {
System.out.println(link+" ==> is a valid link");
}
}
//close the webdriver
driver.quit();
}
}
1条答案
按热度按时间zqdjd7g91#
该页面上的一些链接是电子邮件地址(info@testerscafe.in)。对于电子邮件链接,
url.openConnection()
将返回MailToURLConnection
而不是HttpURLConnection
。您可以排除电子邮件链接,而只使用xpath获取http链接。
代替
使用了
有关starts-with xpath的工作原理,请参见this post。