无法打印菜单名称

时间:2018-08-09 06:24:10

标签: selenium selenium-webdriver xpath

我正在自动化Free CRM网站。当我尝试捕获索引页面上的菜单名称时(登录后),我得到了菜单名称及其子菜单名称(子菜单名称为空白)。我只是对xpath感到恼火,只找到主菜单的xpath。我只想打印菜单名称。

URL https://www.freecrm.com

代码:

@Test
public void Menus() throws Exception {
    driver=new FirefoxDriver();
    driver.get("https://www.freecrm.com/index.html");
    driver.findElement(By.name("username")).sendKeys("XXXXX");
    driver.findElement(By.name("password")).sendKeys("XXXXX");
    driver.findElement(By.xpath("//input[@class='btn btn-small']")).click();
    WebDriverWait wait=new WebDriverWait(driver,20);
    driver.switchTo().frame("mainpanel");
    List<String> LS=new ArrayList<>();
    List<WebElement> Tabs=driver.findElements(By.xpath("//div[@id='navmenu']//li//a[Starts-with(@style,'background')]"));
    for(WebElement Ele:Tabs) {
        LS.add(Ele.getText().trim());
    }
    System.out.println(LS);
    String list=LS.stream().map(Object::toString).collect(Collectors.joining(","));
    System.out.println("List length is.."+list.length());
    String[] X=list.split(",");
    for(int i=0;i<Tabs.size();i++) {
        System.out.println(X[i]);
        FileWriter Fr=new FileWriter("D://MyTxt//k.txt");
        PrintWriter Pw=new PrintWriter(Fr);
        Pw.println(X[i]);
    }
}

截屏:

Highlighted Main menu bar, under those submenu items are there

1 个答案:

答案 0 :(得分:1)

按如下所示更改Xpath,以仅获取菜单名称

//div[@id='navmenu']/ul/li/a

代码:

List<String> LS=new ArrayList<>();
List<WebElement> Tabs=driver.findElements(By.xpath("//div[@id='navmenu']/ul/li/a"));

for(WebElement Ele:Tabs) {
    LS.add(Ele.getText().trim());
}
System.out.println(LS);

输出:

[HOME, CALENDAR, COMPANIES, CONTACTS, DEALS, TASKS, CASES, CALL, EMAIL, TEXT/SMS, PRINT, CAMPAIGNS, DOCS, FORMS, REPORTS]
List length is..105
HOME
CALENDAR
COMPANIES
CONTACTS
DEALS
TASKS
CASES
CALL
EMAIL
TEXT/SMS
PRINT
CAMPAIGNS
DOCS
FORMS
REPORTS