Skip to content

Java code examples added for various locator types #2271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: trunk
Choose a base branch
from

Conversation

harshitBhardwaj97
Copy link
Contributor

@harshitBhardwaj97 harshitBhardwaj97 commented Apr 14, 2025

User description

In this commit i have added the code inside LocatorsTest, for various types of locators (className, id, xpath), and reffered that code in the corresponding documentation files.

This PR intends in helping to "move code" for elements -> locators -> java bindings.

Right now i haven't added the code examples for relative locators, because i felt there are different websites to show the practical code examples for the same.

Although that code is also ready, if you feel its fine, then in the next commit i can include the following code, and make appropriate changes in the documentation files. But in this case, i guess we will have to change the static image (that is currently attached), or give a better context, that how we are using multiple websites to show the relative locators strategies.

public void findElementByAboveRelativeLocator() {
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.saucedemo.com/");

    // Find element by above relative locator
    By emailLocator = RelativeLocator.with(By.tagName("input")).above(By.id("password"));
    WebElement element = driver.findElement(emailLocator);
}

public void findElementByBelowRelativeLocator() {
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.saucedemo.com/");

    // Find element by below relative locator
    By passwordLocator = RelativeLocator.with(By.tagName("input")).below(By.id("user-name"));
    WebElement element = driver.findElement(passwordLocator);
}

public void findElementByLeftOfRelativeLocator() {
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/login.html");

    // Find element by left of relative locator
    By emailLocator = RelativeLocator.with(By.tagName("input")).toLeftOf(By.id("password-field"));
    WebElement element = driver.findElement(emailLocator);
}

public void findElementByRightOfRelativeLocator() {
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/login.html");

    // Find element by right of relative locator
    By passwordLocator = RelativeLocator.with(By.tagName("input")).toRightOf(By.id("username-field"));
    WebElement element = driver.findElement(passwordLocator);
}

public void findElementByNearRelativeLocator() {
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/login.html");

    // Find element by near relative locator
    By loginButtonLocator = RelativeLocator.with(By.id("login-form-submit")).near(By.id("password-field"));
    WebElement element = driver.findElement(loginButtonLocator);
}

public void findElementByChainingRelativeLocators() {
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");

    // Find element by chaining relative locators
    By newsLetterCheckboxLocator = RelativeLocator.with(By.name("newsletter"))
            .toRightOf(By.xpath("//label[@for='newsletter']")).below(By.id("lname"));
    WebElement element = driver.findElement(newsLetterCheckboxLocator);
}

Also i haven't added any assertions, since they were not present before, although if you want i can add assertion and convert each method as a test case too.

I wasn't able to verify the changes by running hugo server cause the required code only doesn't exist, and its being added right now.

Please let me know if any changes are needed.

Thanks for contributing to the Selenium site and documentation!
A PR well described will help maintainers to review and merge it quickly

Before submitting your PR, please check our contributing guidelines.
Avoid large PRs, and help reviewers by making them as simple and short as possible.

Description

Motivation and Context

Types of changes

  • Change to the site (I have double-checked the Netlify deployment, and my changes look good)
  • Code example added (and I also added the example to all translated languages)
  • Improved translation
  • Added new translation (and I also added a notice to each document missing translation)

Checklist

  • I have read the contributing document.
  • I have used hugo to render the site/docs locally and I am sure it works.

PR Type

Documentation, Enhancement


Description

  • Added Java methods for various locator strategies (className, id, cssSelector, etc.) in LocatorsTest.

  • Introduced relative locators and their usage in Java, with examples for above, below, toLeftOf, and toRightOf.

  • Updated formatting, alignment, and examples in locators documentation across multiple languages (Portuguese, Chinese, Japanese, and English).

  • Replaced inline code examples in documentation with references to external Java code files.

  • Improved descriptions, explanations, and clarity for locator strategies in the documentation.


Changes walkthrough 📝

Relevant files
Documentation
locators.pt-br.md
Improved formatting and examples in Portuguese locators documentation.

website_and_docs/content/documentation/webdriver/elements/locators.pt-br.md

  • Updated formatting and alignment of locator strategy tables.
  • Enhanced HTML examples for better readability and consistency.
  • Replaced inline code examples with references to external code files.
  • Improved descriptions and explanations for locator strategies.
  • +275/-271
    locators.zh-cn.md
    Improved formatting and examples in Chinese locators documentation.

    website_and_docs/content/documentation/webdriver/elements/locators.zh-cn.md

  • Updated formatting and alignment of locator strategy tables.
  • Enhanced HTML examples for better readability and consistency.
  • Replaced inline code examples with references to external code files.
  • Improved descriptions and explanations for locator strategies.
  • +274/-271
    locators.ja.md
    Improved formatting and examples in Japanese locators documentation.

    website_and_docs/content/documentation/webdriver/elements/locators.ja.md

  • Updated formatting and alignment of locator strategy tables.
  • Enhanced HTML examples for better readability and consistency.
  • Replaced inline code examples with references to external code files.
  • Improved descriptions and explanations for locator strategies.
  • +276/-270
    locators.en.md
    Improved formatting and added Java code references in locators
    documentation.

    website_and_docs/content/documentation/webdriver/elements/locators.en.md

  • Adjusted formatting and indentation for consistency in the
    documentation.
  • Updated examples to reference Java code snippets from the LocatorsTest
    file.
  • Improved descriptions and explanations for locator strategies and
    relative locators.
  • Enhanced clarity by rephrasing and restructuring some sections.
  • +273/-268
    Enhancement
    LocatorsTest.java
    Added Java examples for locator strategies in Selenium tests.

    examples/java/src/test/java/dev/selenium/elements/LocatorsTest.java

  • Added Java methods for various locator strategies (className, id,
    cssSelector, etc.).
  • Included examples for using By locators and chaining locators.
  • Improved structure and organization of test methods for clarity.
  • Introduced relative locators and their usage in Java.
  • +94/-5   

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • In this commit i have added the code inside LocatorsTest, for
    various types of locators (className, id, xpath), and reffered
    that code in the corresponding documentation files.
    
    This commit intends in helping to "move code" for elements -> locators
    -> java bindings.
    Copy link

    netlify bot commented Apr 14, 2025

    👷 Deploy request for selenium-dev pending review.

    Visit the deploys page to approve it

    Name Link
    🔨 Latest commit 466704d

    Copy link
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Incorrect Method

    The findElementByPartialLinkText method incorrectly uses By.linkText() instead of By.partialLinkText(), which contradicts the method name and intended functionality.

        WebElement element = driver.findElement(By.linkText("Official Page"));
    }
    Syntax Error

    The JavaScript and Kotlin examples for xpath locator contain incorrectly formatted string literals with unescaped single quotes inside single-quoted strings.

    let driver = await new Builder().forBrowser('chrome').build();
    const loc = await driver.findElement(By.xpath('//input[@value='f']'));
    {{< /tab >}}
    {{< tab header="Kotlin" >}}
    val driver = ChromeDriver()
    val loc: WebElement = driver.findElement(By.xpath('//input[@value='f']'))

    Copy link
    Contributor

    qodo-merge-pro bot commented Apr 14, 2025

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Fix mismatched quotes

    The XPath expression has mismatched quotes which will cause a syntax error. The
    single quotes inside the XPath string conflict with the outer single quotes that
    define the string.

    website_and_docs/content/documentation/webdriver/elements/locators.pt-br.md [307-308]

     let driver = await new Builder().forBrowser('chrome').build();
    -const loc = await driver.findElement(By.xpath('//input[@value='f']'));
    +const loc = await driver.findElement(By.xpath("//input[@value='f']"));
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    __

    Why: The suggestion correctly identifies a critical syntax error in the JavaScript code example where nested single quotes in the XPath expression would cause the code to fail. This is a high-impact fix that prevents runtime errors.

    High
    Fix string quote mismatch

    The JavaScript code has syntax errors with mismatched quotes. The string inside
    xpath() is using single quotes, but the string value 'f' is also using single
    quotes, causing a syntax error. Use double quotes for the outer string or escape
    the inner quotes.

    website_and_docs/content/documentation/webdriver/elements/locators.zh-cn.md [306-307]

     let driver = await new Builder().forBrowser('chrome').build();
    -const loc = await driver.findElement(By.xpath('//input[@value='f']'));
    +const loc = await driver.findElement(By.xpath("//input[@value='f']"));
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    __

    Why: The suggestion correctly identifies a syntax error in the JavaScript code where nested single quotes would cause a runtime error. This is a legitimate bug fix that would prevent code execution failures.

    Medium
    Fix string quote syntax

    The Kotlin code has syntax errors with incorrect quotes. Kotlin strings should
    use double quotes, not single quotes. The xpath expression has mismatched quotes
    that will cause a syntax error.

    website_and_docs/content/documentation/webdriver/elements/locators.zh-cn.md [310-311]

     val driver = ChromeDriver()
    -val loc: WebElement = driver.findElement(By.xpath('//input[@value='f']'))
    +val loc: WebElement = driver.findElement(By.xpath("//input[@value='f']"))
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    __

    Why: The suggestion correctly identifies a syntax error in the Kotlin code where the string quotes are improperly formatted. This fix would prevent code execution failures and is an important correction.

    Medium
    Fix nested quotes syntax

    The JavaScript code has syntax errors with nested single quotes. Use different
    quote types for outer and inner strings to avoid syntax errors.

    website_and_docs/content/documentation/webdriver/elements/locators.en.md [315]

    -const loc = await driver.findElement(By.xpath('//input[@value='f']'));
    +const loc = await driver.findElement(By.xpath("//input[@value='f']"));
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    __

    Why: The existing code has improperly nested single quotes which would cause a JavaScript syntax error. The improved code correctly escapes the inner quotes, making the code syntactically valid and executable.

    Medium
    • Update

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    1 participant