How check if element exist in lxml xpath?

4.3k views Asked by At

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 = ""
1

There are 1 answers

0
nguaman On

I think the better way (In my opinion) is using the except.

#valid_xpath = '__VIEWSTATEGENERATOR'
invalid_xpath = 'XXXXXXXX'

try:
    vgenerator = root.xpath('//*[@id="'+ invalid_xpath +'"]//@value')[0]
except IndexError:
    vgenerator = None 

print vgenerator