# -*- coding: utf-8 -*-
#!/usr/bin/python

from lxml import etree

html_str = """
<html>
   <head>
      <title>這是網頁標題</title>
   </head>
   <body>
      <div id="header">
         <h1 id='id1' class='class1'>第一章</h1>
      </div>
      <div id="titles">
         <h1 id='id2' class='class2'>第二章</h1>
         <ul>
            <li id="movie-01" class="movies">
               <a href="01.html">第1節</a>
            </li>
            <li id="movie-02" class="movies">
               <a href="02.html">第2節</a>
            </li>
            <li id="movie-03" class="movies">
               <a href="03.html">第3節</a>
            </li>
            <li id="movie-04" class="movies">
               <a href="04.html">第4節</a>
            </li>
            <li id="movie-05" class="movies">
               <a href="05.html">第5節</a>
            </li>
         </ul>
      </div>
      <div id="test">
         <h1 id='id3' class='class3'>第三章</h1>
      </div>
   </body>
</html>
"""

selector = etree.HTML(html_str)

print(selector.xpath('/html/body/div/h1/text()'))
print(selector.xpath('/html/body/div/h1[1]/text()'))
print(selector.xpath('//h1/text()'))
print(selector.xpath('//h1[@id="id2"]/text()'))

print('--------------------')

r = selector.xpath('//li/a/text()')
for s in r:
   print(s)

print('--------------------')

print(selector.xpath('//li[2]/a/text()'))
print(selector.xpath('//li[4]/a/text()'))

print('--------------------')

print(selector.xpath('/html/body/div/ul/li[3]/a/text()'))
print(selector.xpath('/html/body/div[2]/ul/li[3]/a/text()'))

print(selector.xpath('/html/body/div/ul/li[3]/a/text()')[0])
print(selector.xpath('/html/body/div/ul/li[3]/a')[0].text)
