title: getting the column cell values of a web table using selenium
body: <p>I want to retrieve the text of each cell in a column in a web table. I get the column index from a method and pass it as a parameter to this method:</p>
  
  <pre><code>    public List&lt;String&gt; getColumnValues(int colIndex) {
          WebElement colElement;
          List&lt;String&gt; colValues = new ArrayList&lt;String&gt;();
          List&lt;WebElement&gt; rows = getRows();
          System.out.println("Rows count: " + rows.size());
          Iterator&lt;WebElement&gt; i = rows.iterator();
          while (i.hasNext()) {
              WebElement row = i.next();
              System.out.println("Row data: " + row.getText());
              // How to avoid this check for the header row for each row
              // iteration?
              if (row.findElements(By.tagName("th")).size() &gt; 0) {
                  colElement = row.findElement(By.xpath(".//th[" + colIndex + "]"));
              } else {
                  colElement = row.findElement(By.xpath(".//td[" + colIndex + "]"));
              }
              colValues.add(colElement.getText().trim());
          }
          return colValues;
      }
  </code></pre>
  
  <p>Here is my web table:</p>
  
  <pre><code>&lt;table id = "webtable"&gt;
  &lt;thead&gt;
  &lt;tr&gt;
    &lt;th&gt;Header Column 1&lt;/th&gt;
    &lt;th&gt;Header Column 2&lt;/th&gt;
    &lt;th&gt;Header Column 3&lt;/th&gt;
    &lt;th&gt;Header Column 4&lt;/th&gt;
    &lt;th&gt;Header Column 5&lt;/th&gt;
  &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
  &lt;tr&gt; 
  &lt;td&gt;Row 1 Col 1&lt;/td&gt;
  &lt;td&gt;Row 1 Col 2&lt;/td&gt;
  &lt;td&gt;Row 1 Col 3&lt;/td&gt;
  &lt;td&gt;Row 1 Col 4&lt;/td&gt;
  &lt;td&gt;Row 1 Col 5&lt;/td&gt;
  &lt;/tr&gt;
  &lt;/tbody&gt;
  &lt;tbody&gt;
  &lt;tr&gt; 
  &lt;td&gt;Row 2 Col 1&lt;/td&gt;
  &lt;td&gt;Row 2 Col 2&lt;/td&gt;
  &lt;td&gt;Row 2 Col 3&lt;/td&gt;
  &lt;td&gt;Row 2 Col 4&lt;/td&gt;
  &lt;td&gt;Row 2 Col 5&lt;/td&gt;
  &lt;/tr&gt;
  &lt;/tbody&gt;
  &lt;/table&gt;
  </code></pre>
  
  <p>Issue 1. On line 5, I get the proper count of the rows. But, on line 9, it is not picking up the row (cell) values. Its printing blanks. I was expecting Row 1 Col 1, Row 1 Col 2, Row 1 Col 3 etc.</p>
  
  <p>Issue 2. On line 12, the number of elements with tag "th" returned is only 3, whereas there should be 5.</p>
  
  <p>Issue 3. On line 15, I get a no such element exception trying to find .//td[3] even though I can fetch up to //td[5]</p>
  
  <p>Issue 4. As mentioned in the comment, how can I avoid the check for the header row in each iteration of the row element?</p>
  
  <p>Can anybody please explain what I might be doing wrong or if there is a better way to get the column values returned as a List. I need the collection with the column values so that I can use it in my Hamcrest Matcher assertion using the <code>hasitem(item)</code> to check whether my table contains a certain value.</p>