4

I'm trying to print and/or write to file text inside a span tag from the following HTML. Only want it to find_element once, not find_elements since there's only one instance:

<div>
  <span class="test">2</span>
</div>

Below is the python code I'm using that is generating the "'WebElement' object is not iterable" error.

test = driver.find_element_by_xpath("/html/body/div")

for numberText in test:
numberTexts = numberText.find_element_by_class_name("test")

print(numberTexts.txt)
0

3 Answers 3

12

You're getting a single element (first one) by:

driver.find_element_by_xpath("/html/body/div")

which is obviously not iterable.

For multiple elements i.e. to get an iterable, use:

driver.find_elements_by_xpath("/html/body/div")

Note the s after element.

Also check out the documentation.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Adding "elements" to the first line of code did the trick!
0

single element will not be iterable. Try find_elements_by_xpath (pluralize element).

If there is only one instance, then simply use it without the for loop.

Comments

-1

the error is pretty clear... the return value of find_element_by_xpath is a WebElement. You can't iterate a WebElement...

you have several other mistakes in your example code. You could rewrite the entire block of code as:

element = driver.find_element_by_class_name("test")
print(element.text)

Comments

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.