一个页面上的每个Google review score元素(其中有20个)如this:
在XPath中定义如下:
//ol/div[2]/div/div/div[2]/div[i]/div/div[3]/div/a[1]/div/div/div[2]/div/span
出于某种原因,当我尝试使用以下XPath获取全部20个时,只返回而不是的“无评论”的评论分数:
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']
如果我尝试单独获取这些“无评论”元素,我会得到:
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)
我需要一种方法来填充一个列表或dict,其中包含所有20个评审分数,同时跟踪他们在20个结果中的位置,并且每次遇到“无评审”时填充一个值0。我试着使用三元条件运算符,但很明显,每次复查分数为“No Reviews”时,在语句说else 0
之前,我都会得到NoSuchElementException:
In [30]: mydict[6] = driver.find_element_by_xpath("//ol/div[2]/div/div/div[2]/div[6]/div/div[3]/div/a[1]/div/div/div[2]/div/span").text if driver.find_element_by_xpath("//ol/div[2]/div/div/div[2]/div[6]/div/div[3]/div/a[1]/div/div/div[2]/div/span").text else 0
如何在不触发异常的情况下检查相关元素的不存在或存在?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐