Last active
January 21, 2021 18:19
-
-
Save tonysimpson/8029522 to your computer and use it in GitHub Desktop.
Using Selenium to location and automate elements via thier visible text.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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