简体   繁体   中英

How to move to different tabs in a webpage using selenium webdriver?

I have a scenario where I need to click a tab and enter some text and come back to first tab.

Assuming there are three tabs on page, How do i move to tab2 or tab3 and come back to tab1.

NOTE: I am just talking about tabs, Not windows. I tried all sorts findElement (webdriver's) methods, but no luck. By default i will be on ABSENCE (ie when page first loads). I have to move to EXCEPTIONS tab

I am using java as a code language.

please see below code (TWO HTML TABS: 1) Absence 2) Exceptions). You can see tab name in span tab's.

<td nowrap="nowrap" align="center">
    <a accesskey="A" title="Absence" href="javascript:submitAction_RBET (document.win0,'TAB_BUTTON_ID','TIMESHEET#D');" name="TIMESHEET#D" tabindex="784">
       <span>
          <label class="PTUNDERLINE">A</label> bsence
       </span>
    </a>
</td>
<td nowrap="nowrap" align="center">
    <a accesskey="E" title="Exceptions" href="javascript:submitAction_RBET(document.win0,'TAB_BUTTON_ID','TIMESHEET#E');" name="TIMESHEET#E" tabindex="784">
       <span>
          <label class="PTUNDERLINE">E</label> xceptions
       </span>
    </a>
</td>   

I used below solution to switch over between the tabs.

     new Actions(driver)
    .sendKeys(driver.findElement(By.tagName("html")), Keys.CONTROL)
    .sendKeys(driver.findElement(By.tagName("html")), Keys.NUMPAD2)
    .build().perform();

In above Keys.NUMPAD2 refers that you are gonna move to the second tab in the session.
You can move to Third, Fourth, etc... by giving NUMPAD3, NUMPAD4, etc... respectively.

I hope this will help you.

I have a pretty hacky solution. I was in a similar situation and got around this problem by opening all of the tabs in a new window, by shift-clicking (This was on a Mac so the shortcut might be different on different platforms). It looks something like this:

Actions builder = new Actions(driver); 
Action holdShift = builder.keyDown(Keys.SHIFT).build();
holdShift.perform();
webElement.click();

new Actions(driver).keyUp(Keys.SHIFT).build().perform();
//do something with window handles/names here (can switch between these).

Can you put an id on the a tag?

<a id="tab1"></a>

then use

WebElement tab1 = driver.findElement(By.id("tab1"));
tab1.click();

And if you can't then you have other options:

http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/By.html

XPath would work but I can't say I like writing xpath expressions so I would try css selector. See http://www.w3schools.com/css/css_attribute_selectors.asp Something like this (although this is quite brittle)

By.cssSelector("[title=Absence]");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM