如何找到页面上是否存在文本
如果文本存在,则单击xyz
否则单击abc
。
我正在使用下面的if
语句:
if(driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div/div/div/table/tbody/tr[6]/td[2]")).isDisplayed()) { driver.findElement(By.linkText("logout")).getAttribute("href"); } else { driver.findElement(By.xpath("/html/body/div/div/div/a[2]")).click(); }
脚本失败,并显示以下错误消息:
Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div/div/div/div/div/div/table/tbody/tr[6]/td[2]"}
试试这段代码:
以下代码用于检查整个网页中的文本存在。
if(driver.getPageSource().contains("your Text")) { //Click xyz } else { //Click abc }
如果要检查特定Web元素上的文本
if(driver.findElement(By.id("Locator ID")).getText().equalsIgnoreCase("Yor Text")) { //Click xyz } else { //Click abc }
这里我们可以使用try,除了使用python web驱动程序的函数。 见下面的代码
webtable=driver.find_element_by_xpath("xpath value") print webtable.text try: xyz=driver.find_element_by_xpath(("xpath value") xyz.click() except: abc=driver.find_element_by_xpath(("xpath value") abc.click()
你需要在try catch中包装“IsDisplayed”。 只有元素存在时才能调用“IsDisplayed”。
您可能还想覆盖隐式超时,否则try / catch将需要很长时间。
首先,这种类型的XPath和byLinkText
是非常糟糕的定位器,并且会经常失败。 定位器应该是描述性的,唯一的,不太可能改变 。 优先使用:
- ID
- 类
- CSS ( 比XPath更好的性能 )
- XPath的
然后你可以在元素上使用getText()
而不是整个页面( getPageSource()
),这是更具体的。 对于@Dobbie所说的isDisplayed()
, try catch
也是一个很好的做法,或者更好的是使用FluentWait来查找元素:
// Waiting 10 seconds for an element to be present on the page, checking // for its presence once every 1 second. Wait wait = new FluentWait (driver) .withTimeout(10, SECONDS) .pollingEvery(1, SECONDS) .ignoring(StaleElementReferenceException.class) .ignoring(NoSuchElementException.class) .ignoring(ElementNotVisibleException.class)
然后像这样使用:
wait.until(x -> { WebElement webElement = driverServices.getDriver().findElement(By.id("someId")); return webElement.getText(); }); wait.until(x -> { WebElement webElement = driverServices.getDriver().findElement(By.id("someOtherId")); return webElement.getAttribute("href"); });
试试以下代码: –
Assert.assertTrue(driver.getPageSource().contains(textOnThePage));