环境: pyhton3

一.基础知识

beautiful soup能够对你提供给它的任何格式进行相关的爬取并且进行树形解析,是一个非常优秀的第三方库,它能够对html sml格式进行解析,并且提取其中的相关信息;

首先要安装beautifulsoup

  在cmd命令行输入 pip install beautifulsoup4 (如果安装的是Anaconda 好像就已经安装了,如果想安装其他包 就可以conda install **包的名字)

python 网络爬虫学习笔记之beautifulsoup

这是用anaconda的conda安装的

python 网络爬虫学习笔记之beautifulsoup


接下来 cmd中运行:

import requests

r=requests.get("http://python123.io/ws/demo.html")

r.text 

demo=r.text   

from bs4 import BeautifulSoup      #从besutifulsoup(bs4)库导入BeautifulSoup类 后面的BeautifulSoup要大写 表示类

soup=BeautifulSoup(demo,"html.parser")    #把demo用html解析  soup就代表了解析后的demo页面

print(soup.prettify)    #prettify什么意思 我也不知道

python 网络爬虫学习笔记之beautifulsoup

这就说明beautifulsoup库成功的解析了我们的htlm页面


使用beautifulSoup这个类型有两个参数:第一个是需要beautifulsoup库解析的html格式的信息,另一个就是所使用的解析器(html.parser)

python 网络爬虫学习笔记之beautifulsoup


二BeautifulSoup库的基本元素

beautifulsoup是解析,遍历维护“标签树“的功能库,只要提供的文件是标签类型,beautifulsoup都能进行很好的解释

BeautifulSoup库的引入  from bs4 import BeautifulSoup 

python 网络爬虫学习笔记之beautifulsoup


接下来获取网页上的标签等内容:

from bs4 import BeautifulSoup 

soup=BeautifulSoup(demo,"html.parser')

soup.title    #可以看demo的标题 也就是网页中打开之后显示的标题

tag=soup.a 

tag    #显示tag 也就是a标签的内容

在python的命令行输入以下指令 可以得到:

python 网络爬虫学习笔记之beautifulsoup


查看tag标签的属性用tag.attrs获得:

python 网络爬虫学习笔记之beautifulsoup


可以看到a标签里面属性和属性值按照字典的方式进行存储,所以可以利用以下命令获取属性的值,来看一下tag标签的attrs属性:

python 网络爬虫学习笔记之beautifulsoup


可以看到a标签类型是个字典类型的:

python 网络爬虫学习笔记之beautifulsoup


下面来看一下tag的string类型:

python 网络爬虫学习笔记之beautifulsoup


python 网络爬虫学习笔记之beautifulsoup



三、基于bs4库的html内容遍历方法:

标签树有三种遍历方法:下行遍历,上行遍历,平行遍历

python 网络爬虫学习笔记之beautifulsoup

python 网络爬虫学习笔记之beautifulsoup


利用for,,,in 循环来遍历儿子节点:

python 网络爬虫学习笔记之beautifulsoup


利用 for,,,in循环来遍历子孙节点:

for i in soup.body.decendants:

    print(i)      注意这个地方需要空四个格

python 网络爬虫学习笔记之beautifulsoup


上行遍历:

python 网络爬虫学习笔记之beautifulsoup


在命令行窗口下面运行:

python 网络爬虫学习笔记之beautifulsoup



对于上行树的遍历:

python 网络爬虫学习笔记之beautifulsoup

在命令行实现了一下:

python 网络爬虫学习笔记之beautifulsoup


标签树的平行属性:


python 网络爬虫学习笔记之beautifulsoup

html的平行遍历是有条件的,必须发生在同一个父节点下面的各节点之间


熟悉一下平行遍历的操作指令:

python 网络爬虫学习笔记之beautifulsoup



python 网络爬虫学习笔记之beautifulsoup

cmd中运行了一下:

python 网络爬虫学习笔记之beautifulsoup

总结:

python 网络爬虫学习笔记之beautifulsoup


注意:下行遍历时 contents 返回的是列表;

           children和descendants返回的都是迭代类型 所以只能用在for,,,in循环中;

           平行遍历时 后两个也是返回的迭代类型 只能用在for,,,in循环中


四、基于bs4库的html格式的输出

bs4库的prettify()方法

首先 引入beautifulsoup库 
然后把demo的变量变成soup变量
然后调用prettify()方法
prettify()方法可以为html文本的内容以及标签增加换行符,也可以为每一个标签做换行处理
python 网络爬虫学习笔记之beautifulsoup


相关文章:

  • 2021-08-11
  • 2021-07-02
  • 2021-11-16
  • 2021-09-16
  • 2021-10-11
  • 2021-05-18
  • 2022-01-01
  • 2021-12-05
猜你喜欢
  • 2021-07-27
  • 2021-12-15
  • 2021-12-15
  • 2021-10-07
  • 2021-10-15
  • 2021-05-02
相关资源
相似解决方案