I’m trying to make selenium click Button1
but for some reasons, I get the following error:
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: Button1
I believe the error is happening because it is inside a div
/ul
/li
tag but I can’t either figure out how to do it, I’m stuck.
HTML:
<div id="contentArea"> <div class="pageNavigation" id="pageNavigation"> <ul> <li> <a href="#">Button1</a> </li> <li class="last"> <a href="#">Button2</a> </li> </ul> </div> </div>
Python Code:
from selenium import * driver = webdriver.Firefox() driver.set_window_size(1366, 768, driver.window_handles[0]) driver.get("https://localhost/mypage/index.php") driver.find_element_by_link_text('Button1').click()
Edit: I found out that the html is generated through javascript. my bad.
Advertisement
Answer
You can try the following methods
driver.find_element_by_xpath("//*[text()='Button1']").click()
Or try like you said, to locate the element inside div/ul/li
driver.find_element_by_xpath("//div[@class='pageNavigation']/ul[1]/li[1]/a[1]").click()
And if that doesn’t work for some reason, try with ActionChains
For that, you need to import the module
from selenium.webdriver.common.action_chains import ActionChains
Then use it to click on the element,
this has been a life savior for me in some situations
action = ActionChains(driver) element = driver.find_element_by_xpath("//*[text()='Button1']") action.click(on_element=element).perform()