简体   繁体   中英

How to search for an element using an attribute in selenium and java

I am trying to write some code in selenium that will let me select an element by using the value of the attribute "gamename".

When I inspect the code I get this:

h4 class= "cardTitle_1ifib5" role="gamename">Test Web </h4>

I'm able to select by xpath which is:

"//*[@id="root"]/div/main/article/div[1]/div[1]/a/section/div[1]/h4"

But I want to be able to search by the value of the game name each time so I can search using data providers.

Just to be clear I want to change the "Test Web" part each time i run the function as thats what will be changing. The selector is as follows:

root > div > main > article > div.cards_f1mxfh > div:nth-child(2) > a > section > div.cardTop_1ead8bu > h4

I dont know if this helps or not

Selenium has an option through which you get retrieve attributes of elements. [yourXpath].getAttribute("name");

As per the HTML you have shared and your code trials to identify the element through the value attribute you can use the following Locator Strategy :

  • xpath :

     "//h4[starts-with(@class,'cardTitle_1ifib') and @role='gamename'][normalize-space()='Test Web']" 

You want to find exact text, it seems XPath would be it:

webDriver.findElement(By.xpath("//h4[contains(text(), '" + yourTestLucas + "')]"));

By doing this, you can pass the value to it any time by data providers.

As I read your comments, you can make it as a method:

Case 1 : If you just want to find this element:

public WebElement findElementWithRoleName(String yourTestLucas) {
    return webDriver.findElement(By.xpath("//h4[contains(text(), '" + yourTestLucas + "')]"));
}

Case 2 : If you want to click on this element:

public void clickElementWithRoleName(String yourTestLucas) {
    webDriver.findElement(By.xpath("//h4[contains(text(), '"+ yourTestLucas + "')]")).click();
}

If I understood question correctly, here are few examples how to achive attribute element handling:

1. via css selector:

webDriver.findElements(By.cssSelector("h4[role ='gamename']");

2. via xPath:

webDriver.findElements(By.xpath("//h4[@role='gamename']"))

or

webDriver.findElements(By.xpath("//*[@role='gamename']"))

3. via WebElement method:

WebElement element = driver.findElement(...);
element.getAttribute("role")

Some of this example should work.

Hope this helps.

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