# -*- encoding:utf-8 -*- ''' @Author : dingjiawen @Date : 2023/11/8 16:08 @Usage : @Desc :参考 https://github.com/Python3WebSpider/BeautifulSoupTest ''' html = """
The Dormouse's story
Once upon a time there were three little sisters; and their names were , Lacie and Tillie; and they lived at the bottom of a well.
...
""" from bs4 import BeautifulSoup def baseUse(): soup = BeautifulSoup(html, 'lxml') print(soup.title) #The Dormouse's story
print(soup.p.name) # 获取节点名称 p print(soup.p.attrs) # 获取属性 {'class': ['title'], 'name': 'dromouse'} print(soup.p.attrs['name']) # 获取属性值 dromouse print(soup.p['name']) # 获取属性值 dromouse print(soup.body.p['name']) # 嵌套选择 dromouse print("==========================") def child(): html = """Once upon a time there were three little sisters; and their names were Elsie Lacie and Tillie and they lived at the bottom of a well.
...
""" soup = BeautifulSoup(html, 'lxml') # 子结点 for i, child in enumerate(soup.p.children): print(i, child) print("===============================") # 子孙节点 for i, child in enumerate(soup.p.descendants): print(i, child) print("===============================") def parent(): soup = BeautifulSoup(html, 'lxml') # 父节点 print(soup.a.parent) print("===============================") # 祖父节点 print(type(soup.a.parents)) print(list(enumerate(soup.a.parents))) print("=============================") def brother(): html = """Once upon a time there were three little sisters; and their names were Elsie Hello Lacie and Tillie and they lived at the bottom of a well.
""" # 兄弟节点 soup = BeautifulSoup(html, 'lxml') print('Next Sibling', soup.a.next_sibling) print('Prev Sibling', soup.a.previous_sibling) print('Next Siblings', list(enumerate(soup.a.next_siblings))) print('Prev Siblings', list(enumerate(soup.a.previous_siblings))) # 找到所有满足条件的 def findAll(): html = '''