如何在没有try / except的情况下使用三元条件运算符(或其他)避免异常?

时间:2015-08-26 20:40:30

标签: python python-2.7 if-statement exception-handling ternary-operator

this等网页上的每个Google评论分数元素(其中有20个):

enter image description here

在XPath中定义:

new

出于某种原因,当我尝试使用以下XPath获取所有20个时,只返回 “无评论”的评论分数:

  //ol/div[2]/div/div/div[2]/div[i]/div/div[3]/div/a[1]/div/div/div[2]/div/span

如果我尝试单独获取这些“无评论”元素,我会得到:

In [20]: reviews = driver.find_elements_by_xpath("//ol/div[2]/div/div/div[2]/div[position() >= 1 and position() <= 20]/div/div[3]/div/a[1]/div/div/div[2]/div/span")

In [21]: [i.text for i in reviews]

Out[21]: 
[u'20 reviews',
 u'4 reviews',
 u'4 reviews',
 u'15 reviews',
 u'2 reviews',
 u'7 reviews',
 u'3 reviews',
 u'14 reviews',
 u'2 reviews',
 u'4 reviews',
 u'3 reviews',
 u'30 reviews',
 u'6 reviews',
 u'3 reviews',
 u'2 reviews']

我需要一种方法来一次填充所有20个评论分数的列表或词典,同时跟踪他们在20个结果中的位置,并且每次遇到“无评论”时填充值0。我尝试使用三元条件运算符,但显然每次评论得分为“无评论”时,我会得到NoSuchElementException,然后才能说出NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//ol/div[2]/div/div/div[2]/div[6]/div/div[3]/div/a[1]/div/div/div[2]/div/span"} Stacktrace: at FirefoxDriver.prototype.findElementInternal_ (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/driver-component.js:10299) at FirefoxDriver.prototype.findElement (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/driver-component.js:10308) at DelayedCommand.prototype.executeInternal_/h (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/command-processor.js:12282) at DelayedCommand.prototype.executeInternal_ (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/command-processor.js:12287) at DelayedCommand.prototype.execute/< (file:///var/folders/th/40phk7_13ng3_7zs1rg70plh0000gn/T/tmpoUEQvJ/extensions/fxdriver@googlecode.com/components/command-processor.js:12229)

else 0

如何在不触发异常的情况下检查有问题的元素是否存在或存在?

0 个答案:

没有答案