欢迎来到簟纹灯影的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。

Beautiful Soup 4 方法便捷查询

BS4便捷查询

准备 :

import requests, re
from bs4 import BeautifulSoup, NavigableString

URL = 'www.XXX.com'
res = requests.get(URL)

soup = BeautifulSoup(res.text, 'lxml')  # 使用lxml解析器需要安装C语言库,不想装可以用内置的html.parser, 当然也有其他选项:["lxml-xml"] / "xml" /  "html5lib"

属性

子节点

soup.contents

soup.children 

soup.descendants # 所有子节点

父节点

soup.parent
soup.parents

兄弟节点

soup.next_sibling
soup.next_siblings

soup.previous_sibling
soup.previous_siblings

soup.next_element
soup.next_elements

soup.previous_element
soup.previous_elements

格式化输出

soup.prettify()
str(soup)

soup.get_text('|', strip=True) # '|'是分隔符, strip去空白  
soup.text   # 也可以使用 get_text()
soup.string   # 如果只有一个,返回包含的文本信息
soup.strings  # 如果有多个子节点,则返回 None
soup.stripped_strings  # 去除多余空格空行

搜索文档树

soup.find()
soup.find_all(['a','b']) # 查找这两个标签
soup.find_all(re.complie("^b"))  # 过滤器
soup.find_all(True) # 所有Tag,不会返回字符串节点

soup.find_all(匹配方法)  # 自定义方法 teturn True | False

soup.find_all(name, attrs, recursive, string, **kwargs)
# name : tag 的 name 如 : img
# attrs : tag 的 属性 如 : class
# BS4会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False
# string : 匹配包含的文本信息
# kwargs : 如 id="123"
# limit : 限制最多返回多少个

soup.title(string=True) # 等同于soup.title.find_all(string=True)

soup.find_parent()
soup.find_parents()
...

soup.select(selector)  # selector : 标签选择器
soup.select_one()

修改文档树

soup = BeautifulSoup('<b class="boldest">Extremely bold</b>')
tag = soup.b

tag.name = "div"
tag["class"] = "cls"
tag.string = "New String"

tag.append("str")
new_tag = soup.new_tag("tag_name", href="http://...")
tag.append(new_tag)
tag.insert(index, "str")
tag.insert_before("str" | tag)
tag.insert_after()

tag.clear() # 清楚标签内文本
tag.extract()      # 将当前tag移除文档树,并作结果返回
tag.decompose()    # 将当前tag移除文档树,并完全销毁
tag.replace_with() # 将当前tag移除文档树,并作结果返回 且用新的节点替换

tag.wrap(soup.new_tag("div")) # 用div包装
tag.a.unwrap() # 解包,移除tag内的所有a标签,并返回
posted @ 2019-12-30 19:22  簟纹灯影  阅读(224)  评论(0编辑  收藏  举报