Skip to content

Conversation

karan96108
Copy link

Add child node traversal methods to Element class

Problem

Currently users need to switch between requests-html and lxml.etree to work with child nodes,
creating unnecessary complexity.

Implementation

Added two methods to Element class:

  • children property - Returns list of direct child elements
  • getchildren() method - Provides lxml.etree compatibility

Breaking Changes

None. Adds new functionality while maintaining backwards compatibility.

Usage

# Using property
for child in element.children:
    print(child.tag)

# Using lxml-compatible method 
for child in element.getchildren():
    print(child.tag)

Comment on lines 391 to 401
@property
def children(self) -> List['Element']:

"""Returns a list of child elements."""
return [Element(element=child, url=self.url, default_encoding=self.default_encoding)
for child in self.element.getchildren()]

def getchildren(self) -> List['Element']:
"""Returns a list of child elements (lxml compatibility method)."""
return self.children
def attrs(self) -> _Attrs:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @karan96108, just found this PR by chance. Would suggest this change:

Suggested change
@property
def children(self) -> List['Element']:
"""Returns a list of child elements."""
return [Element(element=child, url=self.url, default_encoding=self.default_encoding)
for child in self.element.getchildren()]
def getchildren(self) -> List['Element']:
"""Returns a list of child elements (lxml compatibility method)."""
return self.children
def attrs(self) -> _Attrs:
@property
def children(self) -> List['Element']:
"""Returns a list of child elements."""
return [Element(element=child, url=self.url, default_encoding=self.default_encoding)
for child in self.element.getchildren()]
def getchildren(self) -> List['Element']:
"""Returns a list of child elements (lxml compatibility method)."""
return self.children
@property
def attrs(self) -> _Attrs:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants