How to click on the element using Selenium and Python

Viewed 233

I want to click on "create post" button of this element:

<div class="l61y9joe j8otv06s a1itoznt qwtvmjv2 kiex77na lgsfgr3h mcogi7i5 ih1xi9zn ippphs35 a53abz89" data-hover="tooltip" data-tooltip-display="overflow" id="js_2f">Create Post</div>

But this id (id="js_2f") has a random value:

I did it this way but didn't work !

wait = WebDriverWait(self.browser, 20)
wait.until(EC.element_to_be_clickable((By.XPATH,  "//*[text()='Create Post' and contains(@id, 'js_')]"))).click()

How can i click on it Using Xpath method ?

4 Answers

Following should help:

driver.find_element_by_xpath('//div[contains(text(),"Create Post")]').click()

You can try below xpath with contains

//div[contains(text(),'Create Post')]

You can try to perform a click on this element using link text

driver.find_element_by_link_text("Create Post")

or

driver.find_element_by_xpath("//div[text() = 'Create Post']")

The Create Post button is a JavaScript enabled element, so to click on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[data-hover='tooltip'][data-tooltip-display]"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@data-hover='tooltip' and text()='Create Post'][@data-tooltip-display]"))).click()
    
  • Note : You have to add the following imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
Related