我写了简单的程序,检查URL状态代码。但是Eclipse给我错误说HttpResponseCode不能被解析为一个类型。我该怎么办。
import static org.testng.Assert.assertEquals;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
public class StarWarSocialMenu {
public static void main(String[] args) throws Exception {
String sDriverPath = "C:\\BrowserDriver\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", sDriverPath);
int statusCode;
final String URL = "https://www.starwars.com/";
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().setScriptTimeout(10000, TimeUnit.SECONDS);
driver.get(URL);
driver.manage().window().maximize();
List<WebElement> socialMenu = driver.findElements(By.xpath("//div[@id='nav-external-links']//a"));
//System.out.println("Total Amenities " + socialMenu.size());
for (WebElement e : socialMenu)
{
//System.out.println(e.getAttribute("href"));
String href = e.getAttribute("href");
statusCode = new HttpResponseCode().httpResponseCodeViaGet(href);
if(200 != statusCode) {
System.out.println(href + " gave a response code of " + statusCode);
}
}
}
}
我该怎么办?如果jar文件需要从哪里可以下载即可。
按硒的webdriver How to get Response Status Code with Selenium WebDriver有检查响应状态代码没有直接的方法,所以我们必须使用另一个库。您可以使用Apache HttpClient或REST-assured library from Jayway。
要使用httpResponseCodeViaGet()
你必须下载并使用下面的导入方法:
import io.restassured.RestAssured;
然后你可以使用:
new HttpResponseCode().httpResponseCodeViaGet("http://www.google.com");
作为替代,您可以使用HttpURLConnection类和openConnection()
,您可以采用如下方案:
package demo;
import java.net.HttpURLConnection;
import java.net.URL;
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;
public class BrokenLinks {
public static void main(String[] args) throws Exception {
String sDriverPath = "C:\\Utility\\BrowserDrivers\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", sDriverPath);
String statusCode;
final String URL = "https://www.starwars.com/";
WebDriver driver = new ChromeDriver();
driver.get(URL);
driver.manage().window().maximize();
List<WebElement> socialMenu = driver.findElements(By.xpath("//div[@id='nav-external-links']//a"));
System.out.println("Total Amenities " + socialMenu.size());
for (WebElement e : socialMenu)
{
String href = e.getAttribute("href");
System.out.println(e.getAttribute("href"));
HttpURLConnection connection = (HttpURLConnection) new URL(href).openConnection();
connection.connect();
statusCode = connection.getResponseMessage();
connection.disconnect();
if(!statusCode.contains("200")) {
System.out.println(href + " gave a response code of " + statusCode);
}
}
}
}