2

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.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
user3245610
  • 33
  • 1
  • 7

3 Answers3

2

$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 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:

$0


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 or .

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

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

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']"));

enter image description here

The invisible one is descendant of a div that has class = "VlcLAe" but no "FPdoLc" so that's the difference.

Mate Mrše
  • 7,997
  • 10
  • 40
  • 77
0

You are getting two values while using //input[@aria-label='Google Search']

enter image description here

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)

enter image description here

Atul
  • 857
  • 8
  • 14