我有这样的结构,我有x路径/html/body/div/div[2]/p[3]
。我如何检查元素的存在:Total topics
,Total posts
,Total members
,Our 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"))
但它不起作用。我怎么能正确地做到这一点?
答案 0 :(得分:1)
假设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");