Everton Reis
Everton Reis

Reputation: 442

XPath: Get text given condition in another DIV

I am trying to get text from a structure like this:

...
  <div class="a">
    <div class="a">
      <div class="a">
        <div class="inner">
          <a>
            <div class="a">...</div>
            <div class="a">&gt;</div>
            <div class="important class">Some interisting text</div>
            <div class="a">...</div>
          </a>
          <a>
            <div class="a">
              <button class="criterion A">...</button>
            </div>
          </a>
        </div>
      </div>
    </div>
  </div>
  <div class="a">
    <div class="a">
      <div class="a">
        <div class="inner">
          <a>
            <div class="a">...</div>
            <div class="a"/>
            <div class="important class">Some interisting text</div>
            <div class="a">...</div>
          </a>
          <a>
            <div class="a">
              <button class="criterion B">...</button>
            </div>
          </a>
        </div>
      </div>
    </div>
  </div>

...

What I want is:
get the path to text from div with class="important class" that matches the criterium where button has a class="B" attribute.

As I am using selenium, I tried something like the following to retrieve a list of XPaths:

list_xpath = driver.find_elements_by_xpath('.//div[@class="importante class" and .//button[@class="cirterion B"]]')

But it returns an empty list.
To retrieve the text, I would do later:

for path in list_xpath:
   print(path.text)

What is the proper way to get these text given a criterion that is in another branch?

Upvotes: 1

Views: 133

Answers (2)

zx485
zx485

Reputation: 29022

You can get the text() value Some interisting text by using the following XPath-1.0 expression:

//div[a/div/@class='important class' and a/div/button/@class='criterion B']/a/div[@class='important class']/text()

In a whole Python expression this would be:

list_xpath = driver.find_elements_by_xpath("//div[a/div/@class='important class' and a/div/button/@class='criterion B']/a/div[@class='important class']/text()")

Upvotes: 2

JaSON
JaSON

Reputation: 4869

Try this XPath:

//a[.//button[@class="cirterion B"]]/preceding-sibling::a//div[@class="importante class"]

Upvotes: 4

Related Questions