简体   繁体   中英

How check if element exist in lxml xpath?

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.

#valid_xpath = '__VIEWSTATEGENERATOR'
invalid_xpath = 'XXXXXXXX'

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

print vgenerator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM