1

I am new to selenium xpath and here's a code I tried. It doesn't enter the loop at all. I think the paths are right. Can someone help? Thanks in advance.

a = driver.find_elements_by_xpath('//*[@class="one"]/ul/li')
for li in a:
     xval =  driver.find_element_by_xpath('.div/text()')`

<div class="one">
	<ul>
		<li><div id="1">Hi</div></li> 
		<li><div id="2"> Hello</div></li> 
		<li><div id="3">Bye</div></li> 
	</ul>
</div>

2 Answers 2

2

You can search child element by querying parent element. Also check the length of the parent element, does it have anything?

a = driver.find_elements_by_xpath('//*[@class="one"]/ul/li')
print len(a)
for li in a:
     xval =  li.find_element_by_xpath('div/text()')
Sign up to request clarification or add additional context in comments.

Comments

1

In selenium find_element_by_xpath() method should return WebElement, but not text content.

Try to replace

xval = driver.find_element_by_xpath('.div/text()')

with

xval = driver.find_element_by_xpath('./div').text

Also note that you should use ./div instead of .div to match div that is direct child of current element

Update

If your loop make no iteration try to wait until required div appears in DOM as it might be generated dynamically:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By. XPATH, "//div[@class="one" and ./ul/li])))

1 Comment

Thank you. I made those changes. But it doesn't enter the loop in the first place. Why is that ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.