Alessandro Buffoli
Alessandro Buffoli

Reputation: 11

How to construct an xpath in Selenium with Python for the given HTML

I'am using Selenium with python to execute an operation on telegram web, I get the web page, select the right group but when I try to enter I have to click "OK" or "Cancel", I want to click ok, but I can't figure out the right way to do it!

The situation is:

<button class="btn btn-md btn-md-primary" 
ng-switch="type" ng-click="$close(data)" 
ng-class="{'btn-md-danger': type == 'RESET_ACCOUNT' || type == 'HISTORY_LEAVE_AND_FLUSH' 
|| type == 'HISTORY_FLUSH_AND_DELETE' || type == 'HISTORY_FLUSH'}" my-focused="">
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!---->
  <!----><span ng-switch-default="" my-i18n="modal_ok" class="" style="">OK</span><!---->
</button>

the xpath is ://*[@id="ng-app"]/body/div[6]/div[2]/div/div/div[2]/button[2]/span

I've tryied a lot of different configurations, from the most easier browser.find_element_by_tag_name('//span[text()="OK"]').click to something weird browser.find_element_by_xpath('//div[6]/div[2]/div/div/div[2]/button[2][contains(@span, "ng-switch-default")]').click but I can't figure out how to click on that "OK" in the <span> tag

Upvotes: 1

Views: 166

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193058

As per the HTML you have shared to click on the element with text as OK as it is an Angular element you have to induce WebDriverWait for the element to be clickable as follows:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC    
# other lines of code
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-md btn-md-primary' and @ng-switch='type']//span[contains(.,'OK')]"))).click()

Upvotes: 1

Related Questions