0

I am trying to use 'count', an XPATH function, to count the number of child nodes a HTML element has.

elements = request.html.xpath('//*[@class="some class"]')
for e in elements:
    print(e.xpath('count(*)')

I am using the Requests-HTML library, so each e in elements is an Element class instance.

However, when I run the code above, an error is received:

TypeError: 'float' object is not iterable

Any ideas?

Edit:

extended code:

from requests_html import HTML
from requests_html import HTMLSession

session = HTMLSession()
r = session.get('https://www.python.org/')
element = r.html.xpath('//*[@id="about"]')
for e in element:
    print(e.xpath('count(*)'))
4
  • Syntax error in what way? It returns all the elements that have a specified class.
    – woxiangqiu
    Commented Sep 20, 2021 at 12:05
  • Yes, you are right. I had made that mistake when writing the code here, but is correct in the actual code.
    – woxiangqiu
    Commented Sep 20, 2021 at 12:07
  • I suggest you make an minimal reproducible example so that it's actually possible to copy your code and reproduce your issue.
    – Tomalak
    Commented Sep 20, 2021 at 12:08
  • 1
    I added an extended code, let me know how it goes.
    – woxiangqiu
    Commented Sep 20, 2021 at 12:19

1 Answer 1

0

You are trying to get the count of children. Without having read the source code of requests_html, here is my best guess of what happens.

  • The expression count(*) gets evaluated. It returns a number.
  • The .xpath() method tries to return a list of matching nodes.
  • It unconditionally tries to iterate the XPath result to build that list, leading to 'float' object is not iterable. This is probably a bug.

Work-around

from requests_html import HTML
from requests_html import HTMLSession

session = HTMLSession()
r = session.get('https://www.python.org/')
element = r.html.xpath('//*[@id="about"]')
for e in element:
    print(len(e.xpath('*')))

Similarly, errors also occur for expressions such as string(*) or normalize-space(*).

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.