介绍
BeautifulSoup是一种可以从html和xml中快速提取内容的python库,共有四种类型,对于爬虫解析来说,主要用其中的遍历文档树和搜索文档树。BeautifulSoup最主要的功能是从网页抓取数据,Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。BeautifulSoup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快,推荐使用lxml 解析器。
引用
Beautiful Soup库,也叫beautifulsoup4或bs4
Beautiful Soup库解析器
bs4库的基本元素
理解
通过beautifulsoup的解析,使得标签树变为一个我们可以操作的beautifulsoup类的变量
BeautifulSoup对应一个HTML/XML文档的全部内容。
我们首先利用requests库中的get来获取包含服务器资源的response对象,之后利用text获取页面的内容,定义为demo,之后利用BeautifulSoup来解析此demo页面,获得一个BeautifulSoup类的soup
爬取网页http://python123.io/ws/demo.html
内容
源代码
<html><head><title>This is a python demo page</title></head>
<body>
<p class="title"><b>The demo python introduces several python courses.</b></p>
<p class="course">Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
<a href="http://www.icourse163.org/course/BIT-268001" class="py1" id="link1">Basic Python</a> and <a href="http://www.icourse163.org/course/BIT-1001870001" class="py2" id="link2">Advanced Python</a>.</p>
</body></html>
爬取页面代码如下
import requests
from bs4 import BeautifulSoup
r = requests.get("http://python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo , "html.parser")
print(type(soup))
<class 'bs4.BeautifulSoup'>
利用类中的基本元素对soup进行分析
1、tag
soup.tag 其中tag为标签的类型,如
print(soup.title)
<title>This is a python demo page</title>
#注意:若代码中含有多个此类型的标签,则返回的是第一个标签
搜索文档对象的方法:
使用find_all(name, attrs, recursive, text, ** kwargs)
- name:按照字符串搜索,可以传入的内容为字符串,正则表达式,列表
- kwargs参数,用来表示属性
- text:对应tag的文本值
像调用 find_all() 一样调用tag
find_all() 几乎是Beautiful Soup中最常用的搜索方法,所以我们定义了它的简写方法. BeautifulSoup 对象和 tag 对象可以被当作一个方法来使用,这个方法的执行结果与调用这个对象的 find_all() 方法相同,下面两行代码是等价的:
soup.find_all(“a”)
soup(“a”)
这两行代码也是等价的:
soup.title.find_all(text=True)
soup.title(text=True)
此处引用自 https://www.cnblogs.com/zipon/p/6129280.html