Terrence Brannon
Terrence Brannon

Reputation: 4968

selenium: locating an element within a WebDriver element

It is a fact that I can locate the exact elements I want with this XPath:

//table[@class="summary-table"]/tbody/tr/*/*/*/a[contains(@class, "snippet-title")]

I know this because I have an XPath plugin that highlights detected elements.

I want to split this element traversal into two parts. The first part returns a list of tr cells and the second part does a search in each tr cells for the a within each one of interest.

The first part to return the tr cells is written and working:

  @property
  def product_elements(self):
    xpath = '//table[@class="summary-table"]/tbody/tr'
    elems = self.driver.find_elements_by_xpath(xpath)
    return elems

However, I have tried various XPath and css selectors in the code below:

  @property
  def product_names(self):
    xpath = '//a[contains(@class, "lc-snippet-title")]'
    for product_elem in self.product_elements:
      elem = product_elem.find_element_by_css_selector('.lc-snippet-title')
      logging.debug("Found this element {0}".format(
          self.pretty_printer.pformat(elem)))
      yield elem.text

and nothing is working to find the a that I want within the tr WebDriver element.

Because there are multiple a tags within the tr, I must find the one I want by the class attribute.

Upvotes: 0

Views: 720

Answers (2)

user3487861
user3487861

Reputation: 350

Given Info: XPath://table[@class="summary-table"]/tbody/tr///*/a[contains(@class, "snippet-title")]

Step 1:

Let us convert the above XPath to CSS Selector for Performance.

XPath://table[@class="summary-table"]/tbody/tr CSS:css=table.summary-table a.snippet-title > tbody > tr

Step 2: Then we can find the CSS Count via given below method

@property

def product_elements(self):

css = 'css=table.summary-table > tbody > tr'

elems = self.driver.find_elements_by_by_css_selector(css)

return elems

@property

def product_names(self):

for product_elem in self.product_elements:
  elem = product_elem.find_element_by_css_selector('.lc-snippet-title')
  logging.debug("Found this element {0}".format(
      self.pretty_printer.pformat(elem)))
  yield elem.text

Upvotes: 0

Furious Duck
Furious Duck

Reputation: 2019

I don't know exactly about CSS selector, but if you have a WebElement with xpath //table[@class="summary-table"]/tbody/tr and it has a child //a[contains(@class, "lc-snippet-title")], the next code works just fine for me:

element = driver.find_element_by_xpath("//table[@class="summary-table"]/tbody/tr")
child = element.find_element_by_xpath(".//a[contains(@class, "lc-snippet-title")]")

The whole point is in . in the beginning of the child element's XPath locator which represents that it is actually a child. Try this

Upvotes: 1

Related Questions