Home > Mobile >  Selenium Python how to find //span number between two values
Selenium Python how to find //span number between two values

Time:12-12

HTML Sample:

<div >
<span>50</span>
</div>
<div >
<span>55</span>
</div>
<div >
<span>25</span>
</div>
<div >
<span>45</span>
</div>
<div >
<span>25</span>
</div>
<div >
<span>30</span>
</div>
<div >
<span>25</span>
</div>
<div >
<span>15</span>
</div>
<div >
<span>10</span>
</div>

In selenium chrome webdriver. I am trying to find the first span that is between range of numbers (10-20), in this case 15, then click it. If nothing on this page(throw NoSuchElementException), click the next page button and loop back try again:

        while True:
            try:
                driver.find_element(By.XPATH, "//span[number(.)= <10, >20]").click()
                time.sleep (1)
                break
            except NoSuchElementException:
                driver.find_element(By.XPATH, "//*[@class='anticon anticon-right']").click()                     
                time.sleep (1)

Tried to use range as well:

price = range (10,20) 
driver.find_element(By.XPATH, "//span[number(.)= 'price']").click()

Please advise.

CodePudding user response:

You can store all web element with XPath //span[text()] in a list like below, and then iterate using a loop and put a condition if int(span_text.text) < 10 and int(span_text.text) >20.

Code:

while True:
    try:
        list_of_span_tag_text = driver.find_elements(By.XPATH, "//span[text()]")
        for span_text in list_of_span_tag_text:
            if int(span_text.text) < 10 and int(span_text.text) >20:
                span_text.click()
                time.sleep(1)
                break
            else:
                print("None of the span on this page satisfy this condtion, span_text.text <10 and span_text.text > 20")
    except NoSuchElementException:
        driver.find_element(By.XPATH, "//*[@class='anticon anticon-right']").click()
        time.sleep(1)

Update 1:

while True:
    try:
        list_of_span_tag_text = driver.find_elements(By.XPATH, "//span[text() < 20][text() > 10]")
        for span_text in list_of_span_tag_text:
            span_text.click()
            time.sleep(1)
            break
        else:
            print("None of the span on this page satisfy this condtion, span_text.text < and span_text.text > 20")
    except NoSuchElementException:
        driver.find_element(By.XPATH, "//*[@class='anticon anticon-right']").click()
        time.sleep(1)

CodePudding user response:

You can try: while 1:

   click = 0 #remains 0 if no spans are in range 10-20
       try:
           lst = driver.find_element(By.XPATH, "//span[number()>10][number()<20]")
           click = len(lst)
           if(click!=0):
               lst[0].click
       except NoSuchElementException:
           #code for next page.    
     

Please comment below if you face any issue.

  • Related