|
# -*- coding: utf-8 -*- |
|
r"""w3BooksTest.py Tests the W3Schools XPath Examples using Python-Lxml and .\byLXMLcopy\books.xml |
|
Usage: ./w3BooksTest.py |
|
Sample: ./w3BooksTest.py |
|
see: [XPath Examples](https://www.w3schools.com/xml/xpath_examples.asp) |
|
[lxml >> Parsing from strings and files](https://lxml.de/tutorial.html#parsing-from-strings-and-files) |
|
[The lxml.etree Tutorial](https://lxml.de/tutorial.html) |
|
""" |
|
import os, sys |
|
import lxml.etree # N.B. import lxml then using lxml.etree DOESN'T WORK |
|
|
|
def w3BooksTest(): |
|
""" |
|
use python to mimic the w3schools [XPath Examples](https://www.w3schools.com/xml/xpath_examples.asp) |
|
[github gist - sekineh/python3_lxml.md](https://gist.github.com/sekineh/f4638c55df2f3e7f28a04a1fa9ea53d9) `body = tree.xpath('//body')` |
|
""" |
|
# [github gist - sekineh/python3_lxml.md](https://gist.github.com/sekineh/f4638c55df2f3e7f28a04a1fa9ea53d9) `body = tree.xpath('//body')` |
|
tree = lxml.etree.parse('books.xml') # (some_file_or_file_like_object) |
|
|
|
print() |
|
path = "/bookstore/book/title" |
|
titles = tree.xpath(path) # https://www.w3schools.com/xml/tryit.asp?filename=try_xpath_select_cdnodes |
|
print('type(titles): %s'%(type(titles))) |
|
print('titles: %s'%(titles)) |
|
|
|
print() |
|
# equivalent of [XPath Examples](https://www.w3schools.com/xml/xpath_examples.asp) |
|
for t in titles: |
|
print('t.text: %s'%(t.text)) # Just a guess but it WORKED! |
|
|
|
print() |
|
print("""let's try the next w3schools example == "/bookstore/book[1]/title" """) |
|
xpath = "/bookstore/book[1]/title" |
|
resultL = tree.xpath(xpath) |
|
print('resultL[0].text: %s'%(resultL[0].text)) |
|
|
|
print() |
|
print("""next example Select all the prices == "/bookstore/book/price[text()]" """) |
|
xpath = "/bookstore/book/price[text()]" |
|
resultL = tree.xpath(xpath) |
|
for r in resultL: |
|
print('r.text: %s'%(r.text)) |
|
|
|
print() |
|
print("""next example Select price nodes with price>35 == "/bookstore/book[price>35]/price" """) |
|
xpath = "/bookstore/book[price>35]/price" |
|
resultL = tree.xpath(xpath) |
|
for r in resultL: |
|
print('r.text: %s'%(r.text)) |
|
|
|
print() |
|
print("""next example Select *title* nodes with price>355 == "/bookstore/book[price>35]/title" """) |
|
xpath = "/bookstore/book[price>35]/title" |
|
resultL = tree.xpath(xpath) |
|
for r in resultL: |
|
print('r.text: %s'%(r.text)) |
|
|
|
|
|
def main(): |
|
print('ORIG os.getcwd(): %s'% ( os.getcwd() ) ) |
|
print('__file__: %s'% ( __file__ ) ) |
|
print('dirpath(__file__): %s'% ( os.path.split(__file__)[0] ) ) |
|
print('__name__: %s'% ( __name__ ) ) |
|
os.chdir(os.path.split(__file__)[0]) |
|
print('NEW os.getcwd(): %s'% ( os.getcwd() ) ) |
|
w3BooksTest() |
|
if __name__ == '__main__': |
|
main() |