Home > Mobile >  Xpath to locate element using text() and @class as conditions
Xpath to locate element using text() and @class as conditions

Time:06-23

I am trying to automate adding items to cart in online shop, however, I got stuck on a loop that should differentiate whether item is available or not.

Here's the loop:

while True:
        #if ???
            WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//*[text()='"   size.get()   "']"))).click()
            sleep(1)
            WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//*[text()='Add to cart']"))).click()
            sleep(1)
            print("Success!")
            break
        else:
            driver.refresh()
            sleep(3)

If the size is available, button is active:

<div >
    <button aria-checked="false" role="radio" >
        <span >XL</span>
        <span >
        </span>
    </button>
</div>

If not, button is inactive:

<div >
    <button disabled="" aria-checked="false" role="radio" >
        <span >XXL</span>
        <span >
        </span>
    </button>
</div>

The question is: what should be the condition for this loop?

I have tried something like this:

if (driver.find_elements(By.XPATH, "//*[contains(@class='styles__ArticleSizeButton-sc-1n1fwgw-0 jIVZOs') and text()='"   e2.get()   "']")):

EDIT: Replaced "=" with "," in the above code as follows:

if (driver.find_elements(By.XPATH, "//*[contains(@class='styles__ArticleSizeButton-sc-1n1fwgw-0 jIVZOs') and text()='"   e2.get()   "']")):

but I keep getting invalid xpath expression error.

EDIT: The error is gone, but the browser keeps refreshing with the else statement (element not found).

CodePudding user response:

I believe your error is in the use of the contains function, which expects two parameters: a string and a substring, although you're passing it a boolean expression (@class='styles__ArticleSizeButton-sc-1n1fwgw-0 jIVZOs').

I expect this is just a typo and you actually meant to type contains(@class, 'styles__ArticleSizeButton-sc-1n1fwgw-0 jIVZOs') (NB comma instead of an equals sign after @class).

Also, you are looking for a button element which has a child text node (text() refers to a text node) which is equal to the size you're looking for, but that text node is actually a child of a span which is a child of the button. You can compare your size to the text value of that span.

Try something like this:

"//*[contains(@class='styles__ArticleSizeButton-sc-1n1fwgw-0 jIVZOs') and span='"
  e2.get() 
  "']"

CodePudding user response:

e3="Some value"
x=f"//button[contains(@class,'styles__ArticleSizeButton-sc-1n1fwgw-0 jIVZOs') and not(contains(@disabled='')) and ./span[contains(text(),'{e3}')]])]"
print(x)

Try looking for the button which contains that class and with that span and maybe check if button disabled?

  • Related