要获取祖父元素,可以使用BeautifulSoup中的find_parents()方法。该方法返回所有匹配元素的祖先元素列表。我们可以使用该方法来获取祖父元素。
例如:
grandparent = soup.find('li', {'class': 'grandparent'}).find_parents()[0]
这里我们先定位到一个class为grandparent的li元素,然后使用find_parents()来获取祖先,再通过[0]来选择第一个祖先元素,也就是祖父元素。
对于子级li元素,我们可以使用find_all()方法。该方法返回所有匹配元素的列表。我们可以通过指定参数来定位子级li元素。
例如:
children = soup.find('ul', {'class': 'parent'}).find_all('li', {'class': 'child'})
这里我们先定位到一个class为parent的ul元素,然后使用find_all()来获取所有子级li元素,再通过参数{'class': 'child'}来指定定位条件,选择class为child的子级li元素。