Home > Mobile >  How to check if an element exists in the HTML using Selenium
How to check if an element exists in the HTML using Selenium

Time:03-20

I have a question. I find an element on the pages using the class, and display the text from there, and then split() it disassembles, but there is an error when there is no element, it does not parse.

Code:

spans =  driver.find_elements(By.XPATH, "//span[@class='ipsContained ipsType_break']")

for span in spans:
    atag = span.find_element(By.XPATH, ".//a")
    print(atag.get_attribute('href'))
    urlik = atag.get_attribute('href')
    driver.get(url=urlik)
    time.sleep(2)
    urla = driver.find_element(By.CLASS_NAME, "ipsPagination_pageJump").text
    for page_number in range(int(urla.split()[3])):
        page_number = page_number   1
        driver.get(url=urlik   f"page/{page_number}")
        time.sleep(2)
        imgs = driver.find_elements(By.CLASS_NAME, "cGalleryPatchwork_image")
        for i in imgs:
            driver.execute_script("arguments[0].scrollIntoView(true);", i)
            time.sleep(0.2)
            print(i.get_attribute("src"))

I need check this:

urla = driver.find_element(By.CLASS_NAME, "ipsPagination_pageJump").text

CodePudding user response:

Instead of

urla = driver.find_element(By.CLASS_NAME, "ipsPagination_pageJump")

Use

urla = driver.find_elements(By.CLASS_NAME, "ipsPagination_pageJump")
if urla:
    urla[0].text

find_elements method returns a list of web elements matching the passed locator.
So, in case such element(s) existing urla will be a non-empty list while non-empty list is interpreted in Python as a Boolean True.
In case no matching elements found urla will be an empty list while empty list is interpreted in Python as a Boolean False.

CodePudding user response:

To attempt to find an element on the pages using the class and display the text from there inrespective of the element is present or not you can wrap up the code in a try-except{} block handling the NoSuchElementException as follows:

driver.get(url=urlik)
time.sleep(2)
try:
    urla = driver.find_element(By.CLASS_NAME, "ipsPagination_pageJump").text
    for page_number in range(int(urla.split()[3])):
        page_number = page_number   1
        driver.get(url=urlik   f"page/{page_number}")
        time.sleep(2)
        imgs = driver.find_elements(By.CLASS_NAME, "cGalleryPatchwork_image")
        for i in imgs:
            driver.execute_script("arguments[0].scrollIntoView(true);", i)
            time.sleep(0.2)
            print(i.get_attribute("src"))
except NoSuchElementException:
    print("Element is not present")
  • Related