我要解決的問題是這樣的:我正在嘗試從網頁中抓取一些內容,我正在使用 seleniumfindElementByClassName
來獲取元素內容,并且到目前為止它作業得很好。但是考慮到我正在抓取的網站更改了 html 中的其中一個元素類,我不想讓could not find element exception
其余的代碼不執行并直接跳到 catch 塊中。
我的想法是將每一行代碼放入一個 try catch 塊中,但是我想要抓取大約 15 個欄位會使代碼看起來很難看。你自己看:
String name = null;
String type = null;
String description = null;
try {
driver.get(link);
try {
name = driver.findElementByClassName(environment.getProperty("booking.propertyName")).getText();
}catch (Exception e){
log.error("error doing thing");
}
try {
type = driver.findElementByClassName(environment.getProperty("booking.propertyType")).getText();
}catch (Exception e){
log.error("error doing thing");
}
try {
description = driver.findElementByClassName(environment.getProperty("booking.propertyDescription")).getText();
}catch (Exception e){
log.error("error doing thing");
}
}catch (Exception e){
log.error("Error during scraping");
}
因此,如果其中一個出現問題,我仍然希望其余代碼繼續運行,而不是在有一個 try-catch 塊時,第一個失敗的事情會阻止其他事情的執行。上面的代碼作業得很好,但看起來不太好,所以我的問題是你有什么想法讓我看起來更好看。
uj5u.com熱心網友回復:
這沒有靈丹妙藥。但是避免重復代碼的標準方法是重構。例如:
try {
type = driver.findElementByClassName(environment.getProperty("something"))
.getText();
} catch (Exception e){
log.error("error doing thing");
}
可以改寫為:
type = getElementTextIgnoringExceptions(driver, environment, "something");
wheregetElementTextIgnoringExceptions
被定義為這樣的東西:
public String getElementTextIgnoringExceptions(
Driver driver, Environment env, String name) {
try {
String className = env.getProperty(name);
return driver.findElementByClassName(className).getText();
} catch (Exception ex) {
log.error("error getting " name, ex);
return null;
}
}
但是...您在此處嘗試簡化的代碼有一些不好的地方:
- 抓
Exception
是不好的。你不知道你會抓住什么,或者繼續下去是否安全或明智。 - 不記錄例外是不好的。如果您的日志檔案中有“錯誤操作”訊息,您將如何診斷問題?
- 在例外之后繼續(在您的應用程式的背景關系中)可能會導致問題。您的其余代碼將充滿
null
檢查以處理無法獲取的元素(或其他)。錯過一張支票,您可能會獲得 NPE;例如,在單元測驗中沒有涵蓋的某些邊緣情況下。
這些問題比使代碼看起來更好更重要。
如果您使用的是 Java 8 ,則可以進行重構,以便將邏輯作為 lambda 運算式傳遞。這取決于所用變數的性質。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/458704.html
上一篇:Ada83例外是否包括資源清理?