Search code examples
pythonseleniumwebdriverautomated-tests

Selecting an element by tag name with specific text in Selenium


I have this HTML

<div class="callout callout-accordion" style="background-image: url(&quot;/images/expand.png&quot;);">
    <span class="edit" data-pk="bandwidth_bar">Bandwidth Settings</span>
    <span class="telnet-arrow"></span>
</div>

I'm trying to select span with text = Bandwidth Settings, and click on the div with class name = callout.

if driver.find_element_by_tag_name("span") == ("Bandwidth Settings"):
    print "Found"
    time.sleep(100)
    driver.find_element_by_tag_name("div").find_element_by_class_name("callout").click()

print "Not found"
time.sleep(100)

I kept getting

Testing started at 1:59 PM ...
Not found

Process finished with exit code 0

What did I miss?


Select the parent div

    if driver.find_element_by_xpath("//span[text()='Bandwidth Settings']") is None:
        print "Not Found"
    else:
        print "Found"
        span = driver.find_element_by_xpath("//span[text()='Bandwidth Settings']")
        div = span.find_element_by_xpath('..')
        div.click()

I got

WebDriverException: Message: unknown error: Element


Solution

  • One way would be to use find_element_by_xpath(xpath) like this:

    if driver.find_element_by_xpath("//span[contains(.,'Bandwidth Settings')]") is None:
       print "Not found"
    else:
       print "Found"
       ...
    

    For an exact match (as you asked for in your comment), use "//span[text()='Bandwidth Settings']"

    On your edited question, try one of these:

    Locate directly (if there is no other matching element):

    driver.find_element_by_css_selector("div[style*='/images/telenet/expand.png']")
    

    Locate via span (provided there isn't any other div on that level):

    driver.find_element_by_xpath("//span[contains(.,'Bandwidth Settings')]/../div")