Selenium 4.0 中的相对定位器是什么?
Selenium 4.0 中的相对或友好定位器可通过元素的 tagname 属性获得。
above() - 关于指定元素,位于其上方的 Web 元素。
语法 -
driver.findElement(withTagName(“<<tagnamevalue>>”).above(element));
below() - 关于指定元素,位于其下方的 Web 元素。
语法 -
driver.findElement(withTagName(“<<tagnamevalue>>”).below(element));
toLeftof() - 关于指定元素,位于其左侧的 Web 元素。
语法 -
driver.findElement(withTagName(“<<tagnamevalue>>”).toLeftOf(element));
toRightOf() - 关于指定元素,位于其右侧的 Web 元素。
语法 -
driver.findElement(withTagName(“<<tagnamevalue>>”).toRightOf(element));
使用相对定位器的代码实现。
示例
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import static org.openqa.selenium.support.locators.RelativeLocator .withTagName; public class RelLocator { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://tutorialspoint.com/about/about_careers.htm"; driver.get(url); // maximizing browser with maximize() river.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); WebElement head_label = driver.findElement(By.cssSelector("li[class='heading']")); // getting the link text just below head_label web element String txt = driver.findElement(withTagName("a").below(head_label)) .getText(); System.out.println("The text below heading is " + txt); WebElement write = driver.findElement(By.xpath("//a[text()='Write for us']")); // getting the heading just above Write for us web link String txtabove = driver.findElement(withTagName("li").above(write)) .getText(); System.out.println("The text above link is " + txtabove); WebElement searchinp = driver.findElement(By.xpath("//input[@name='search']")); // getting the search button to the right of edit box searchinp. driver.findElement(withTagName("button").toRightOf(searchinp)) .click(); WebElement prntlnk = driver.findElement(By.xpath("//a[@class=' hide-on-mobile']")); // getting the previous page link to the left of prntlnk. String prevlink = driver.findElement(withTagName("a").toLeftOf(prntlnk)) .getText(); System.out.println("The text left of link is " + prevlink); driver.close(); } }
广告