Skip to content

Instantly share code, notes, and snippets.

@tonysimpson
Last active January 21, 2021 18:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonysimpson/8029522 to your computer and use it in GitHub Desktop.
Save tonysimpson/8029522 to your computer and use it in GitHub Desktop.
Using Selenium to location and automate elements via thier visible text.
# Note I haven't executed this code it's
# written from memory - its purpose is
# as an example.
from selenium import webdriver
wd = webdriver.Firefox()
# ... open a website etc.
wd.find_element_by_xpath('//*[text()="Some Text"]') # finds first element where the text content is "Some Text"
# This function shows how easy it is to
# match any visible text using selenium.
# for a real implementation you would want to
# consider which attributes may be visible
# rather than search every attribute (to avoid
# false positives). Also it doesn't behave
# correctly if nothing is found.
def find_element_by_visible_text(wd, text):
"""Finds any element by visible text.
"""
xpath = '//*[@*="{0}" or text()="{0}"]'.format(text)
found = [elem for elem in wd.find_elements_by_xpath(xpath)
if elem.is_displayed()]
return found[0]
find_element_by_visible_text(wd, "Username or email").send_keys('agjasimpson')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment