How to handle duplicate elements in selenium, where duplicate elements comes marked with ==$0
?
Go to www.google.com and search for google search button, I have tried iterator and creating list, but, is this correct way of handling ==$0
driver.findElements(By.xpath("//input[@aria-label='Google Search']"));
I want to select second element.
$0 - $4
The $0
, $1
, $2
, $3
and $4
are the historical reference to the last five DOM elements inspected within the Elements panel of google-chrome-devtools or the last five JavaScript heap objects selected in the Profiles panel. $0
returns the most recently selected element or JavaScript object, $1
returns the second most recently selected one, and so on.
In your usecase, you have inspected the Google Search button through the Elements panel. So in the Console drawer, $0
has been evaluated and displays the same element as:
A bit more information about your usecase would have helped us to answer your question in a better way. However every element within the HTML DOM can be identified uniquely using either css-selectors or xpath.
If your usecase is to Google Search any particular term/phrase, you can use the following solution:
WebElement searchField = driver.findElement(By.name("q"));
searchField.sendKeys("user3245610");
searchField.sendKeys("Keys.RETURN");
You can find a detailed relevant discussion in How to click a random link from google search results through Selenium and Python
The visible button that you would like to click is descendant of the div with "FPdoLc VlcLAe" class so you can select it with
driver.findElements(By.xpath("//div[@class='FPdoLc VlcLAe']//input[@name='btnK']"));
The invisible one is descendant of a div that has class = "VlcLAe" but no "FPdoLc" so that's the difference.
You are getting two values while using //input[@aria-label='Google Search']
One of the possible solution is to use: (//input[@aria-label='Google Search'])[ 2 ] (the value in the solid brackets i.e. 2 should be without spaces)
Eg - driver.findElement(By.xpath("(//input[@aria-label='Google Search'])[ 2 ]"); //(the value in the solid brackets i.e. 2 should be without spaces)
来源:https://stackoverflow.com/questions/56389906/selenium-duplicate-elements-marked-with-0