If you want to select the direct parent node of a node , Need to use parent attribute , If you want to select all the parent nodes of a node , Need to use parents attribute .parent Property returns the name of the parent node of the current node Tag object , and parents Property returns an iteratable object , adopt for Loop can iterate over the object , And get the corresponding values of all parent nodes of the current node Tag object .
The following example passes parent Attribute gets a The immediate parent node of the node , And then use parents Attribute gets a Node all the parent nodes , And through iteration , Output a The tag names of all parent nodes of the node .
from bs4 import BeautifulSoup
html = '''
<html>
<head>
<meta charset="UTF-8">
<title>Beautiful Soup demonstration </title>
<tag1><xyz><b></b></xyz></tag1>
</head>
<body>
<div>
<ul>
<li class="item1" value = "hello world">
<a href="https://geekori.com">