I am having a very strange issue using selenium and xpath. I am having a page that renders 25 <a>
's with nested <img/>
tags. I need to get using findElements()
all this elements. If i get the page source and search trough the text the following substring: "alt="Expand List"" i get 25 appearances. But when i execute the command let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]"))
I get 32 items. I logged the items in google chrome and to the list are added <a>
's that contain images with different alt values. Any ideas? The piece of code:
let text = await driver.getPageSource();
var count = (text.match(/alt="Expand List"/g) || []).length;
let items = await driver.findElements(By.xpath("//a[//img[contains(@alt,'Expand List')]]"))
console.log(count, items.length); //outputs 25, 32
Your xpath should be more like:
//a/img[contains(@alt,'Expand List')]
One slash indicates it's a child of the parent //a
.
I highly recommend getting a brower addon to test xpaths. One that I use almost everyday is ChroPath. You can also test xpaths in the devtools console with something like
$x('//a/img[contains(@alt,'Expand List')]')
Will give output like this:
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.