Uri
Uri

Reputation: 3291

Is it possible to make this Xpath shorter?

We develop extensions for Chrome, Firefox and Safari and we test our Chrome and Firefox extensions with Selenium. We have a specific element which can be either span or div (depends on the version of our extension), and we need to validate it with Selenium. The code looks like this:

WebDriverWait(driver=self.driver, timeout=30).until(expected_conditions.visibility_of_element_located((By.XPATH, "//span[@id='top-icon'] | //div[@id='top-icon']")))
self.assertEqual(first=1, second=len(self.driver.find_elements_by_xpath(xpath="//span[@id='top-icon'] | //div[@id='top-icon']")))

I would like to know if there is a way to write the xpath shorter (without writing the id twice), but not try to find any element (only span or div).

Upvotes: 1

Views: 761

Answers (2)

alecxe
alecxe

Reputation: 473873

To make an element-agnostic expression, use a * in place of div or span:

//*[@id='top-icon']

Or, just use a By.ID locator:

(By.ID, "top-icon")

Upvotes: 0

Michael Kay
Michael Kay

Reputation: 163322

You could use

//*[self::span|self::div][@id='top-icon']

Upvotes: 1

Related Questions