1

I have the HTML code as:

<a class="a-size-base a-link-normal review-title a-color-base a-text-bold" data-hook="review-title" href="/gp/customer-reviews/R252N8IFRXV8TW/ref=cm_cr_getr_d_rvw_ttl?ie=UTF8&ASIN=B071NZZHF9">Security concern</a>

and i have to search the element by data-hook as the class name is common for other attributes also and href and link-text are dynamic as it is changing for the next element as there are multiple elements that i need to fetch.

Can i search it by data-hook. If yes could someone help me with it!

3 Answers3

1

Sure you can.

CSS:

driver.findElement(By.cssSelector("a[data-hook='review-title']"));

Xpath:

driver.findElement(By.xpath("//a[@data-hook='review-title']"));
Fenio
  • 3,528
  • 1
  • 13
  • 27
0

You can also use the below code if multiple data-hook item you need.

List<WebElement> list = driver.findElements(By.className("review-title"));

for(WebElement elem : list){
    System.out.println(elem.getAttribute("data-hook"));
}
Mahmud Riad
  • 1,169
  • 1
  • 8
  • 19
0

As per the HTML you have shared to find the element through data-hook attribute you can use the following line of code :

driver.findElement(By.xpath("//a[@data-hook='review-title']"));

Though you mentioned class name is common it will be a good practice to keep the class name attribute in the xpath as follows :

driver.findElement(By.xpath("//a[@class='a-size-base a-link-normal review-title a-color-base a-text-bold' and @data-hook='review-title']"));

Further, though you mentioned href is changing, I will suggest to use the combination of all the three attributes to uniquely identify the element as :

driver.findElement(By.xpath("//a[@class='a-size-base a-link-normal review-title a-color-base a-text-bold' and contains(@href,'/gp/customer-reviews/') and @data-hook='review-title']"));
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Hi @DebanjanB i tried using all the above solution but i was not able to click the element. I tried giving wait of 20 seconds by using WebDriverWait, but still no luck. – Anshul Srivastava Dec 06 '17 at 06:30