0

I am working on a webtable that doesn't have an ID or a class name. This is how the table looks like in HTML view

<table style ="border-style:layout-fixed">
  <tbody>
   <tr>
    <td>

and so on

how do i refer this table in selenium web driver?

Ratz
  • 1
  • 3

2 Answers2

1

Finding the element

When you neither have a class name nor an id to uniquely identify an element, there is XPath. It describes, where an element within the DOM is and is able to select it. An XPath string might look like this:

html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]/div/h4[1]/b

For more info, see e.g. XPath in Selenium WebDriver: Complete Tutorial

How to get the XPath to your table?

In Firefox, you can install the FirePath addon. This adds a tab in the developer tools. Simply select the element and copy the XPath.

For Chrome there is XPath Helper which basically does the same.

Accessing the element in your code?

Now that you have the element, you need to access it in your code. The following Java code will get you the element (and click on it; Source):

d.findElement(By.xpath("<XPATH HERE>")).click();

If you are using Python, the code looks a little different (Source):

from selenium.webdriver.common.by import By
driver.find_element(By.XPATH, '//button[text()="Some text"]')
Community
  • 1
  • 1
rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
0

Adding to @rollstuhlfahrer detailed answer: 1. You can also use CssSelector 2. Even though you can have FirePath or Chrome generate the XPath (or CssSelector) for you, often it's not the best option, as this XPath is not necessarily the most maintainable one. Note that there are many XPath expressions that can refer to the same element. This means that it may become invalid due to application changes more often than others. The rule of thumb is to use the expression that relies on the least amount of details that are likely to change. 3. Assuming you're using Selenium for test automaton (and not any other site scraping goal), then the best option is to ask the developers to add an id attribute to the table element, or a unique class to be used specifically by your test automaton. This way you can rely on a single detail which is very unlikely to change.

Arnon Axelrod
  • 1,444
  • 2
  • 13
  • 21