{"id":10,"date":"2020-11-08T13:26:53","date_gmt":"2020-11-08T13:26:53","guid":{"rendered":"https:\/\/automationbyrain.com\/?p=10"},"modified":"2020-11-09T09:11:06","modified_gmt":"2020-11-09T09:11:06","slug":"how-to-get-element-with-selenium-webdriver","status":"publish","type":"post","link":"https:\/\/automationbyrain.com\/?p=10","title":{"rendered":"How to Get Element with Selenium Webdriver"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">In order to interact with the UI of a web application, we need to have a WebElement object.<br>Here\u2019s a (very) simple example of getting an element from \u201cgoogle.com\u201d:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Navigate to&nbsp;<a href=\"http:\/\/www.google.com\/\">www.google.com<\/a><\/li><li>Right click + inspect element<\/li><li>Find a unique identifier (id\/class name)&nbsp;<\/li><li>Use selenium \u201cfindElement(By)\u201d<\/li><\/ol>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/h2MHTlfYUwfPktEQIWkHjuX9nrWtAHVQ8NDkR1mvDZmNZ0MGSYax24c8GIerpqKIT4Lj5kCNw9KwYIlHPon6JXZhV2WSFd4TnnpzvuUt-a3KjV9Y9hkPRMpz3FLRmv8mKI1csufj\" alt=\"google chrome - inspect element\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>\nWebDriver driver;\n\n@Test\npublic void getElementTest()\n{\n   driver  = new ChromeDriver();\n   driver.get(\"http:\/\/wwww.google.com\");\n\n   WebElement element = driver.findElement(By.className(\"RNNXgb\"));\n }\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">POSSIBLE PROBLEMS WITH THE CODE ABOVE<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The code isn\u2019t generic and not reusable.<\/strong><br>The default Selenium design will throw an exception, which will fail your test<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>What happens in case the element is not found?&nbsp;<\/strong><br>The default Selenium design will throw an exception, which will fail your test.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Is it good?<\/strong>&nbsp;I personally don\u2019t think that basing your tests on possible exceptions is a good practice, that\u2019s why \u201cWe got to take the power back\u201d<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">POSSIBLE SOLUTIONS TO THE CODE ABOVE<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First,&nbsp; we will move our code to a seperate method, so we would be able to access it from multiple tests:&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public WebElement getElementByClassName(String className)\n{\n    WebElement element;\n    try\n    {\n        element = driver.findElement(By.className(className));\n     }\n     catch (Exception e)\n     {\n         element = null;\n     }\n     return element;\n }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Explanation:<br>Our method is using a \u201ctry\u201d and \u201ccatch\u201d blocks. Why? As was mentioned earlier, in case the element wasn\u2019t found, Selenium will throw an exception which will fail our test. By enforcing a return value, we can decide in our test, what to do next: fail the test, try again, try a different identifier or whatever<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\npublic void getElementTest()\n{\n    driver  = new ChromeDriver();\n    driver.get(\"http:\/\/wwww.google.com\");\n\n    WebElement element = this.getElementByClassName(\"RNNXgb\");\n }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, we\u2019re now using a reference to our new method and we don\u2019t need to be afraid of any exception.<br>Let\u2019s say now that we want to use an \u201cid\u201d. We can write the same method for using an id:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public WebElement getElementById(String id)\n{\n    WebElement element;\n    try\n    {\n        element = driver.findElement(By.id(id));\n    }\n    catch (Exception e)\n    {\n        element = null;\n    }\n    return element;\n }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Voila! but\u2026 wait! Did you recognize a problem with our code?&nbsp;<br>Yes, you are right: Both methods are practically the same beside the identifier. It means that we now need to maintain two methods with similar characteristics separately.<br>What can we do? We can merge them into one \u201cparent\u201d method:&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public WebElement getElementBy(By by)\n{\n    WebElement element;\n    try\n    {\n       element = driver.findElement(by);\n    }\n    catch (Exception e)\n    {\n        element = null;\n    }\n    return element;\n } <\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, this method is handling the exception, and all we need to do is to access it from our previous methods:&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public WebElement getElementByClassName(String className)\n{\n    return this.getElementBy(By.className(className));\n}\n\npublic WebElement getElementById(String id)\n{\n    return this.getElementBy(By.id(id));\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Needless to say that we don\u2019t need to change anything in our test. For the purpose of this example we will fail the test in case the element is null:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Test\npublic void getElementTest()\n{\n    driver  = new ChromeDriver();\n    driver.get(\"http:\/\/wwww.google.com\");\n\n    WebElement element = this.getElementByClassName(\"RNNXgb\");\n\n    Assert.assertNotNull(element,\"The element is null, failing test!\");\n }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Below you can check out our video tutorial for this article:<\/p>\n\n\n\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"How to get element | findElement wrapper | Advanced Selenium tutorial\" width=\"640\" height=\"360\" src=\"https:\/\/www.youtube.com\/embed\/j2N1jkO1eqg?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In the next article we\u2019ll explain how to get sub element with Selenium.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Enjoy!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In order to interact with the UI of a web application, we need to have a WebElement object.Here\u2019s a (very) simple example of getting an element from \u201cgoogle.com\u201d: Navigate to&nbsp;www.google.com Right click + inspect element Find a unique identifier (id\/class name)&nbsp; Use selenium \u201cfindElement(By)\u201d POSSIBLE PROBLEMS WITH THE CODE ABOVE<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[3],"tags":[5,4,6],"class_list":["post-10","post","type-post","status-publish","format-standard","hentry","category-selenium","tag-getelement","tag-selenium","tag-selenium-tutorial","ct-col-2"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/automationbyrain.com\/index.php?rest_route=\/wp\/v2\/posts\/10","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/automationbyrain.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/automationbyrain.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/automationbyrain.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/automationbyrain.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10"}],"version-history":[{"count":1,"href":"https:\/\/automationbyrain.com\/index.php?rest_route=\/wp\/v2\/posts\/10\/revisions"}],"predecessor-version":[{"id":11,"href":"https:\/\/automationbyrain.com\/index.php?rest_route=\/wp\/v2\/posts\/10\/revisions\/11"}],"wp:attachment":[{"href":"https:\/\/automationbyrain.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/automationbyrain.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/automationbyrain.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}