我想建立一个自动化测试,所以我必须知道在 chrome 的控制台中出现的错误。
是否有一个选项可以获取出现在控制台中的错误行?
要查看控制台:右键单击页面中的某处,单击“检查元素”,然后转到“控制台”。
最佳答案
我不懂 C#,但这是完成这项工作的 Java 代码,我希望你能将它翻译成 C#
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ChromeConsoleLogging {
private WebDriver driver;
@BeforeMethod
public void setUp() {
System.setProperty("webdriver.chrome.driver", "c:\\path\\to\\chromedriver.exe");
DesiredCapabilities caps = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
caps.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
driver = new ChromeDriver(caps);
}
@AfterMethod
public void tearDown() {
driver.quit();
}
public void analyzeLog() {
LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
for (LogEntry entry : logEntries) {
System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage());
//do something useful with the data
}
}
@Test
public void testMethod() {
driver.get("http://mypage.com");
//do something on page
analyzeLog();
}
}
注意上面代码中的setUp方法。我们使用 LoggingPreferences 对象来启用日志记录。有几种类型的日志,但如果您想跟踪控制台错误,那么您应该使用 LogType.BROWSER。然后我们将该对象传递给 DesiredCapabilities 并进一步传递给 ChromeDriver 构造函数,瞧 - 我们有一个启用了日志记录的 ChromeDriver 实例。
在页面上执行一些操作后,我们调用 analyzeLog() 方法。在这里,我们只是提取日志并遍历其条目。您可以在此处提出断言或进行任何其他您想要的报告。
我的灵感是 this code by Michael Klepikov这解释了如何从 ChromeDriver 中提取性能日志。
关于c# - 获取 chrome 的控制台日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261338/