There is a code that is looking for a salary column on a certain site. In most cases it is not there and I get:

weblib.error.DataNotFound: Could not get first item for div[@class="-title"]//span[@class="salary"] query of class XpathSelector 

I try to catch through try - except, but I could not catch either as DataNotFound, nor weblib.error.DataNotFound, or just error. The work of try - except continues through else and a traceback is output.

My code is:

 try: sal = i.select('div[@class="-title"]//span[@class="salary"]') except Exception: jobinfo.update({'salary': 'Null'}) else: sal = int(sal.text()) jobinfo.update({'salary':sal}) 

Traceback calls the line after else:

  Traceback (most recent call last): File "/home/shmulya/Documents/LiClipse Workspace/remoteokpars/parser.py", line 33, in <module> sal = int(sal.text()) File "/usr/local/lib/python2.7/dist-packages/selection/base.py", line 103, in text sel = self.one() File "/usr/local/lib/python2.7/dist-packages/selection/base.py", line 86, in one raise DataNotFound(m) weblib.error.DataNotFound: Could not get first item for div[@class="-title"]//span[@class="salary"] query of class XpathSelector 

How to catch him?

  • except weblib.error.DataNotFound: or except DataNotFound: - Mihail Ris
  • I tried it too. No - still flies to else. - Shmelenduk Irish

1 answer 1

Hmmm, it turned out that you need to put try in another place. Something like this:

 sal = i.select('div[@class="-title"]//span[@class="salary"]') try: sal = int(sal.text()) except IndexError: jobinfo.update({'salary': 'Null'}) print 'ok null' except ValueError: jobinfo.update({'salary': 'Null'}) print 'ok null' else: jobinfo.update({'salary':sal})