How to write XPath to text before some text?

Viewed 203

I am using temporary emails for my selenium project but I've been stuck on this issue for some time. The information always seems to be changing and I cannot figure out how I'm supposed to write it. This is the HTML:

<a href="https://temp-mail.org/en/view/cd89ea25d93a2fed0d182d9d8225b5b" title="" class="viewLink title-subject" data-mail-id="cd89ea25d93a2fed0d182d9d82425b5b">812479 is your Instagram code</a>

I've tried to find the mail-id using various methods that I've read about.

execute = browser.find_element_by_xpath('.//span[@class = "data-mail-id"]') #Attempt 1
execute = browser.find_element_by_xpath('//span[text()="Instagram"]')

I've even copied the full xpath but it always returns Unable to Locate Element However, the data-mail-id and the code changes every time you send an email to your inbox. What do I need to change?

I want the string ("812479") that's followed by " is your Instagram code".

2 Answers

Straight XPath 1.0

This XPath expression,

substring-before(//a[contains(.,' is your Instagram code')][1], 
                 ' is your Instagram code')

will return the substring before ' is your Instagram code' in the first a element that contains that string, or the empty string if no such element exists.


XPath in Selenium

You can select the a element via XPath in Selenium,

a = browser.find_element_by_xpath("//a[contains(.,' is your Instagram code')][1]")

Then access the element's text via a.text and use split() to implement substring-before() (link shows after, but technique is easily adapted to before).

I'm a big fan of using exepected_conditions to avoid timing issues between the page loading and the script execution.

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

myec = EC.visibility_of_element_located(
    (By.XPATH, '//a[contains(text(), "is your Instagram code")]'))

# search for the element on the page until found or TimeoutException is raised
wait = WebDriverWait(driver, timeout)
myelement = wait.until(myec, "Could not find Instagram Code") 
Related