Ic3m4n
Ic3m4n

Reputation: 871

How to chain contains and not-contains in xpath?

How do I chain contains and "not-contains" in xpath?

I want to make sure a button has the class add-to-cart-button and doesn't have the class btn--disabled.

How can I do this? Here is what I have so far:

button[contains(@class, "add-to-cart-button")]

EDIT: In my project I have a list of products. Now I want to select the first Article-Container on the page whose button doesn't have the class btn--disabled

Here is the HTML

<main>
  <div class="grid shop-list__results offer-tiles">
   <div class="offer-tiles__item offer-tiles--odd offer-tiles--top-border">
    <article itemscope="itemscope" itemtype="http://schema.org/Product" class="offer-tile">
     <div itemprop="offers" itemscope="itemscope" itemtype="http://schema.org/Offer" class="offer-tile__content">
      <ul class="offer-tile__actions">
        <li class="offer-tile__action offer-tile__action--add-to-cart">
          <button type="button" class="btn add-to-cart-button btn--disabled">Cart</button></li>
      </ul>
    </div>
  </article>
</div>
<div class="offer-tiles__item offer-tiles--even offer-tiles--top-border">
  <article itemscope="itemscope" itemtype="http://schema.org/Product" class="offer-tile">
    <div itemprop="offers" itemscope="itemscope" itemtype="http://schema.org/Offer" class="offer-tile__content">
      <ul class="offer-tile__actions">
        <li class="offer-tile__action offer-tile__action--add-to-cart">
          <button type="button" class="btn add-to-cart-button">Cart</button></li>
      </ul>
    </div>
  </article>
</div>

And here is my xpath selector so far(this is obviously wrong): //main//article[contains(descendant::button/@class, "add-to-cart-button")][not(descendant::button/@disabled)]

Upvotes: 2

Views: 793

Answers (1)

Andrei
Andrei

Reputation: 5637

Try this:

button[contains(@class, "add-to-cart-button") and not(contains(@class, "btn-disabled"))]

where:

  • and is an operator between two statements. Example //div[x and y] or //div[x or y]
  • not() is for opposite of statement in the function. Example //div[x and not(y)]

EDIT:

As per HTML block you have provided, you can use this xPath:

//button[@class = 'btn add-to-cart-button']

or, if there many add-to-cart-button, you can use something like this:

//div[@class = 'offer-tiles__item offer-tiles--even offer-tiles--top-border']/article[@itemtype = 'http://schema.org/Product']/div[@itemtype = 'http://schema.org/Offer']//button[@class = 'btn add-to-cart-button']

Upvotes: 2

Related Questions