Can not get table header elements
Question: In Python, I have a variable containing an `html` table element obtained like
this:

    
    
    page = requests.get('http://www.myPage.com')
    tree = html.fromstring(page.content)
    table = tree.xpath('//table[@class="list"]')
    

The `table` variable has this content:

    
    
    <table class="list">
          <tr>
            <th>Date(s)</th>
            <th>Sport</th>
            <th>Event</th>
            <th>Location</th>
          </tr>
          <tr>
            <td>Jan 18-31</td>
            <td>Tennis</td>
            <td><a href="tennis-grand-slam/australian-open/index.htm">Australia Open</a></td>
            <td>Melbourne, Australia</td>
          </tr>
    </table>
    

I am trying to extract the headers like this:

    
    
    rows = iter(table)
    headers = [col.text for col in next(rows)]
    print "headers are: ", headers
    

However, when I print the `headers` variable I get this:

    
    
    headers are:  ['\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n
          ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n
    ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n        ', '\n
            ', '\n        ', '\n        ']
    

How can I extract the headers properly?


Answer: **Try this:**

    
    
    from lxml import html
    
    HTML_CODE = """<table class="list">
          <tr>
            <th>Date(s)</th>
            <th>Sport</th>
            <th>Event</th>
            <th>Location</th>
          </tr>
          <tr>
            <td>Jan 18-31</td>
            <td>Tennis</td>
            <td><a href="tennis-grand-slam/australian-open/index.htm">Australia Open</a></td>
            <td>Melbourne, Australia</td>
          </tr>
    </table>"""
    
    tree = html.fromstring(HTML_CODE)
    headers = tree.xpath('//table[@class="list"]/tr/th/text()')
    print "Headers are: {}".format(', '.join(headers))
    

**Output:**

    
    
    Headers are: Date(s), Sport, Event, Location
    

