独自のロケータの作成に問題はないことはわかっていますが、Seleniumはカスタムロケータを作成する機能を備えています。基本的にセレンは、By.id
、By.name
などの要素を見つけるときに、xPath
を使用して要素を配置するために内部的に使用されます。By
クラスを拡張することで、簡単に独自のロケータを作成できます。
あなたがtestid
を使用して要素を見つけカスタムロケータを作成したい場合、あなたは(あなたは、Javaを使用していると仮定すると)以下のように作成する必要があります: -
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
class ByTestId extends By {
private final String testId;
public ByTestId(String testId) {
this.testId = testId;
}
@Override
public List<WebElement> findElements(SearchContext context) {
return context.findElements(By
.xpath(".//*[@testid = '"+testId+"']"));
}
@Override
public WebElement findElement(SearchContext context) {
return context.findElement(By
.xpath("//*[@testid = '"+testId+"']"));
}
}
今、あなたは簡単に以下のようにtestid
を使用して要素を見つけることができます: -
//for single webelement
WebElement element = driver.findElement(new ByTestId("addbutton"));
//for list of webelements
List<WebElement> elements = driver.findElements(new ByTestId("addbutton"));
注:またとしてBy.cssSelector
を使用してカスタムBy
クラスの要素を見つけることができます。By.cssSelector("*[testid = '"+testId+"']")
はそれが役に立てば幸い.. :)
なぜあなたはそれが単にBy.xpath'など '、' By.cssSelector'を見つけることができながら、独自のカスタムセレクタを作成しようとしています...?あなたの目的を具体化してください... –
理由が更新された質問 –