Python BeautifulSoup库入门

版权声明:转载标明出处即可 https://blog.csdn.net/hpu2022/article/details/90138000

BeautifulSoup安装方法:
以管理员的身份启动cmd
执行 pip install BeautifulSoup4

使用方法:
from bs4 import BeautifulSoup
soup = BeautifulSoup(<p>data</p>, 'html.parser')
bs4是BeautifulSoup4的简称
<p>data</p> 是爬取网页得到的信息,一般会用一个变量保存
html.parser是解析方法

Beautiful Soup库,也叫beautifulsoup4 或 bs4
约定引用方式如下,即主要是用BeautifulSoup类
from bs4 import BeautifulSoup
import bs4

每一个HTML文档都相当于是一个标签树
BeautifulSoup就是对这些标签树进行解析

解析器              使用方法                             条件
bs4的HTML解析器     BeautifulSoup(mk,'html.parser')     安装bs4库
lxml的HTML解析器    BeautifulSoup(mk,'lxml')            pip install lxml
lxml的XML解析器     BeautifulSoup(mk,'xml')             pip install lxml
html5lib的解析器    BeautifulSoup(mk,'html5lib')        pip install html5lib

BeautifulSoup类的基本元素
<p class=“title”> … </p>
基本元素            说明
Tag                     标签,最基本的信息组织单元,分别用<>和</>标明开头和结尾
Name                 标签的名字,<p>…</p>的名字是'p',格式:<tag>.name
Attributes           标签的属性,字典形式组织,格式:<tag>.attrs
NavigableString 标签内非属性字符串,<>…</>中字符串,格式:<tag>.string
Comment           标签内字符串的注释部分,一种特殊的Comment类型


标签树的下行遍历
属性                   说明
.contents           子节点的列表,将<tag>所有儿子节点存入列表
.children            子节点的迭代类型,与.contents类似,用于循环遍历儿子节点
.descendants    子孙节点的迭代类型,包含所有子孙节点,用于循环遍历

BeautifulSoup类型是标签树的根节点

标签树的上行遍历
属性          说明
.parent      节点的父亲标签
.parents    节点先辈标签的迭代类型,用于循环遍历先辈节点、

标签树的平行遍历
属性                        说明
.next_sibling           返回按照HTML文本顺序的下一个平行节点标签
.previous_sibling    返回按照HTML文本顺序的上一个平行节点标签
.next_siblings         迭代类型,返回按照HTML文本顺序的后续所有平行节点标签
.previous_siblings  迭代类型,返回按照HTML文本顺序的前续所有平行节点标签

所有的平行遍历必须发生在同一个父亲节点下
一个标签的平行节点可能不是一个标签
任何一个标签它的平行标签是可能会存在 NavigableString类型的


使用prettify()可以使HTML页面更加友好的显示

code:

import requests
from bs4 import BeautifulSoup

r = requests.get("http://python123.io/ws/demo.html")
r.encoding = r.apparent_encoding
demo = r.text
soup = BeautifulSoup(demo, "html.parser")
# filename = open("C:\\Users\张成龙\Desktop\my.html", "w")
# tag = soup.a
# # print(tag.attrs['href'])
# # print(soup , file=filename)
# # filename.close()

# 下行遍历
for child in soup.body.children:
    print(child)

# 上行遍历
for parent in soup.a.parents:
    if parent is None:
        print(parent)
    else:
        print(parent.name)

# # 平行遍历
# print(soup.a.next_sibling.next_sibling)
# print(soup.a.previous_sibling)
# print(soup.a.previous_sibling.previous_sibling)
# print(soup.a.parent)
# # 后续
for sibling in soup.a.next_siblings:
    print(sibling)
# # 前续
for sibling in soup.a.previous_siblings:
    print(sibling)

# bs4库的prettify()方法
# print(soup.prettify())
print(soup.a.prettify())

猜你喜欢

转载自blog.csdn.net/hpu2022/article/details/90138000
今日推荐