Each of the Google review score elements (of which there are 20) on a page such as this:
is defined in XPath thus:
//ol/div[2]/div/div/div[2]/div[i]/div/div[3]/div/a[1]/div/div/div[2]/div/span
For some reason, when I try fetch all 20 with the following XPath, only the review scores that are not 'No reviews' get returned:
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']
If I try to fetch these 'No reviews' elements individually, I get:
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)
I need a way to populate a list or dict with all 20 review scores in one go, while keeping track of their position in the 20 results, and populating a value of 0 every time 'No Reviews' is encountered. I tried using the ternary conditional operator, but I obviously I will get the NoSuchElementException each time a review score is 'No Reviews', before the statement gets to say else 0
:
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
How can I check for the non-presence or presence of the element in question without triggering an exception?
Aucun commentaire:
Enregistrer un commentaire