from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(open('ex1.html'), 'lxml')
# print(soup)
# print(type(soup))
# print(soup.p) #获取各个节点
# print(soup.a)
# print(soup.a.attrs) #节点内的属性
# print(list(soup.ul.stripped_strings)) #节点内文本 stripped_strings去除所有的空格
# print(soup.ul.contents) #contents返回列表
# print(list(soup.ul.children)) #children返回一个可迭代对象,list转换或for循环打印
# print(list(soup.body.descendants)) #descendants获取所有子孙节点
# print(list(soup.title.parents)) #父节点
# for i in soup.title.parents:
# print(i.name)
# print(soup.head)
# print(list(soup.a.next_siblings)) #next_sibling获取当前节点前面的文本内容
# print(list(soup.a.previous_siblings)) #previous_sibling获取当前节点后面的文本内容
# print(soup.find_all('div')[1].find('p')) #find_all(name)名称查找
# print(soup.find_all(class_='aaa')) #find_all(attr)属性查找
# print(soup.find_all(text='aaa')) #指定字符串
# print(soup.find_all(text=re.compile('a'))) #正则匹配
# for i in soup.find_all(text=re.compile('a')):
# print(i)
# print(soup.select('html head title')) #css选择器
# print(soup.select_one('.aaa')) #.类
# print(soup.select('#bbb')) ##id
# print(soup.select('a')[1].get_text()) #get_text(),.string获取内容
beautifulsoup解析
最新推荐文章于 2024-07-10 11:20:48 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)