0

I am fairly new to Selenium, I am trying to find a Contact info element in a page, and click it if it exists. Many times, what happens is, the element is in all caps such as CONTACT, sometimes Contact and sometimes contact. So I've stored these cases in a variable and I'm using find_element_by_partial_link_text to find the right element and click on it. I'm using exception handling (try and except) and if loop to check each condition. This is my code:

from selenium import webdriver
import time
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException

browser = webdriver.Chrome()
browser.implicitly_wait(30)
browser.maximize_window()

ab = 'Contact'
bc = 'CONTACT'
cd = 'contact'

browser.get('https://www.dominos.co.in/store-location/pune')

try:
    if browser.find_element_by_partial_link_text(ab).is_displayed():
        browser.find_element_by_partial_link_text(ab).click()

    elif browser.find_element_by_partial_link_text(bc).is_displayed():
        browser.find_element_by_partial_link_text(bc).click()

    elif browser.find_element_by_partial_link_text(cd).is_displayed():
        browser.find_element_by_partial_link_text(cd).click()

except NoSuchElementException:
    print("No such element found")
    browser.close()

So if Contact element is present in any webpage, this code is able to click on it, but if other two elements are present, it goes directly into except and prints No such element found. If you guys could help me tackle this scenario, I would really appreciate it :)

2 Answers 2

2

Use xpath with translate() to ignore the case of the text in the html. You can also use find_elements to avoid the try except:

elements = browser.find_elements_by_xpath('//a[translate(text(),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz") = "contact"]')
if elements and elements[0].is_displayed():
    elements[0].click()
Sign up to request clarification or add additional context in comments.

2 Comments

One more thing, suppose I have a webpage in , say Spanish, so how do I grab contact info element, how do I translate it with xpath?
@vesuvius Same way, just replace "ABCDEFGHIJKLMNOPQRSTUVWXYZ" with the Spanish alphabet.
1

Try using translate() functions in xpath ,these functions helps you to deal with case sensitivity.

Hope this helps.

1 Comment

lower-case and matches is xpath 2 functionality, it won't work with selenium.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.