I am automating an internal company webpage that loads its HTML dynamically with javascript. I have been trying to find the XPath for automating a click action (which I did), but somehow while running the script selenium throws an error:
Unable to locate element
The Html content is below:
<mat-nav-list _ngcontent-gki-c5="" dense="" role="navigation">
<div _ngcontent-gki-c5="" style="">Insights</div>
<!----><a _ngcontent-gki-c5="" mat-list-item="" href="/insights/home"><div style="background: rgb(204, 136, 136); border: 2px solid red;">
<div mat-ripple="" style="">
</div>
<div style=""></div>
Your Highlights
</div>
</a><a _ngcontent-gki-c5="" mat-list-item="" href="/insights/downloads"><div style="background: rgb(204, 136, 136); border: 2px solid red;">
<div mat-ripple="" style="">
</div>
<div style=""></div>
Downloads
</div>
</a>
<a _ngcontent-gki-c5="" mat-list-item="" style=""><div style="background: rgb(204, 136, 136); border: 2px solid red;">
<div mat-ripple="" style="">
</div>
<div style=""></div>
Run Insight
<mat-icon _ngcontent-gki-c5="" role="img" aria-hidden="true" data-mat-icon-type="font" style="transform: rotate(180deg);"> expand_more </mat-icon>
</div>
</a>
<!----><!---->
<mat-form-field _ngcontent-gki-c5="" style=""><div >
<div >
<!---->
</div>
</div>
</mat-form-field>
</mat-nav-list>
I want to click on the text "Run insight" from the dynamically generated list. The xpaths that I used are:
//a[@class='mat-focus-indicator ng-tns-c5-1 mat-list-item menu-item text-neutral-l1 font-size-sub-1 active']
//div[contains(text(),'Run Insight')]
//div[contains(@class, 'mat-list-item-content') and normalize-space(text()) = 'Run insight']
Is there a better XPath for the "Run insight" click action? Any suggestions would be appreciated.
CodePudding user response:
The desired element is a dynamic element, so to click on the element with text as Run Insight you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
Using PARTIAL_LINK_TEXT:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Run Insight"))).click()
Using XPATH:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//mat-nav-list//a[@mat-list-item]//div[@class='mat-list-item-content' and contains(., 'Run Insight')]"))).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