0

Hi I am trying access an element in selenium that looks like this when I inspect element:

<div class="im_message_outer_wrap hasselect" ng-click="toggleMessage(historyMessage.mid, $event)" data-msg-id="5973">

I have tried to find element using its xpath as follows:

element = driver.find_element_by_xpath("//div[@class = 'im_message_outer_wrap hasselect'][@data-msg-id='5967']")

This keeps returning an error saying unable to locate element. What am i doing wrong or is there a better way to access this element. The data-msg-ID is important because in the code I want to be able to iterate through ids to grab each element in order.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352

1 Answers1

-1

To locate the element you can use either of the following Locator Strategies:

  • Using css_selector:

    element = driver.find_element(By.CSS_SELECTOR, "div.im_message_outer_wrap.hasselect[ng-click^='toggleMessage']")
    
  • Using xpath:

    element = driver.find_element(By.XPATH, "//div[@class='im_message_outer_wrap hasselect' and starts-with(@ng-click, 'toggleMessage')]")
    

Ideally, to locate the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.im_message_outer_wrap.hasselect[ng-click^='toggleMessage']")))
    
  • Using XPATH:

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='im_message_outer_wrap hasselect' and starts-with(@ng-click, 'toggleMessage')]")))
    
  • 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
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352