简体   繁体   中英

How to click an element with respect to the adjacent element within the HTML DOM using Selenium and Java

I need to click on thumbnail which is appearing right before "Automation-Browser (Meta) Title".

I think I need to use combination of below:

  • Sibling
  • Ancestor
  • Preceding &
  • Descendant

Code trial:

driver.findElements(By.xpath("//div[@class='*foundation-collection-item-title*'][@title='Automation-Browser (Meta) Title']//ancestor::div//coral-columnview-item-thumbnail")).size()`     = Found 52 elements with same property & I do not want to use index.

I just want to click thumbnail which is appearing right before "Automation-Browser (Meta) Title"** in below screenshot.

在此处输入图片说明

Building the xpath off of an image is a bit tough. You may get better answers if you provide a code sample of the page source, but this may get you pointed in the right direction.

//*[contains(text(),"Automation-Browser")]/../preceding-sibling::coral-columnview-item-thumbnail[@class='foundation-colection-item-thumbnail']

Adapted from this similar post: How to use XPath preceding-sibling correctly

To click() on the thumbnail adjacent to the element with text as Automation-Browser (Meta) Title you you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies :

  • Using xpath and title attribute:

     new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='foundation-colection-item-title' and @title=\\"Automation-Browser (Meta) Title\\"]//preceding::coral-columnview-item-thumbnail[1]/img[@class='foundation-colection-item-thumbnail']"))).click();
  • xpath and innerText :

     new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='foundation-colection-item-title' and contains(., 'Automation-Browser')]//preceding::coral-columnview-item-thumbnail[1]/img[@class='foundation-colection-item-thumbnail']"))).click();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM