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:
JavaScript
x
17
17
1
<div id="contentArea">
2
<div class="pageNavigation" id="pageNavigation">
3
<ul>
4
<li>
5
6
<a href="#">Button1</a>
7
8
</li>
9
<li class="last">
10
11
<a href="#">Button2</a>
12
13
</li>
14
</ul>
15
</div>
16
</div>
17
Python Code:
JavaScript
1
8
1
from selenium import *
2
3
driver = webdriver.Firefox()
4
driver.set_window_size(1366, 768, driver.window_handles[0])
5
driver.get("https://localhost/mypage/index.php")
6
driver.find_element_by_link_text('Button1').click()
7
8
Edit: I found out that the html is generated through javascript. my bad.
Advertisement
Answer
You can try the following methods
JavaScript
1
2
1
driver.find_element_by_xpath("//*[text()='Button1']").click()
2
Or try like you said, to locate the element inside div/ul/li
JavaScript
1
2
1
driver.find_element_by_xpath("//div[@class='pageNavigation']/ul[1]/li[1]/a[1]").click()
2
And if that doesn’t work for some reason, try with ActionChains
For that, you need to import the module
JavaScript
1
2
1
from selenium.webdriver.common.action_chains import ActionChains
2
Then use it to click on the element,
this has been a life savior for me in some situations
JavaScript
1
4
1
action = ActionChains(driver)
2
element = driver.find_element_by_xpath("//*[text()='Button1']")
3
action.click(on_element=element).perform()
4