I use lxml xpath
for parsing HTML page in Python 3.
As sample I have code, that finds element HTML:
version_android = doc.xpath("//div[@itemprop='operatingSystems']//text()")
Father I have insert Mysql query:
insert = ("insert into tracks (version) values ('%s')" % (version_android[0]))
Problem is, that if is not element in HTML DOM, therefore I get Mysql error when I try to get parsed result in line: version[0]
and put in query.
Sometimes result array does not have index version_android[0]
, but has index version_android[2]
: It makes error in insert function Mysql.
How can I validate this correct? I have a lot the same rules for parsing.
I tried this, but I dislike this solution:
version_android = doc.xpath("//div[@itemprop='operatingSystems']//text()")
if len(version_android):
version_android = version_android[0]
else:
version_android = ""
I think the better way (In my opinion) is using the except.