简体   繁体   中英

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?

试试这个XPath:

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

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()")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM