我有这样的结构,我有x路径/html/body/div/div[2]/p[3]。我如何检查元素的存在:Total topicsTotal postsTotal membersOur newest member

 <p>
           Total posts
      <strong>1</strong>
          • Total topics
      <strong>1</strong>
          • Total members
      <strong>1</strong>
          • Our newest member
      <strong>
        <a class="username-coloured" style="color: #AA0000;" href="./memberlist.php?mode=viewprofile&u=2&sid=b2d8cf0665bc4dda70a20be1c2801659">Admin</a>
      </strong>
     </p>


我尝试这样做:

form.findElement(By.xpath("/html/body/div/div[2]/p[3]")).getAttribute("value").equalsIgnoreCase(
         "Total posts"))


但这是行不通的。如何正确执行?

最佳答案

假设DOM中没有其他<strong>元素,则可以尝试以下操作:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

List<String> getTitles(String url)
{
    List<String> titles = new ArrayList<String>();
    WebDriver    driver = new FirefoxDriver();
    driver.get(url);
    List<WebElement> strongs = driver.findElements(By.tagName("strong"));
    for (WebElement strong : strongs)
        titles.add(strong.getText());
    driver.quit();
    return titles;
}

boolean checkTitles(List<String> titles,String suffix)
{
    for (String title : titles)
        if (title.endsWith(suffix))
            return true;
    return false;
}


用法示例:

List<String> titles = getTitles("http://www.google.com");
boolean a = checkTitles(titles,"Total topics");
boolean b = checkTitles(titles,"Total posts");
boolean c = checkTitles(titles,"Total members");
boolean d = checkTitles(titles,"Our newest member");

09-10 08:39
查看更多