BeautifulSoup是一个可以从HTML或XML文件中提取数据的Python库,它能实现文档的导航和查找,修改文档等操作
官方文档地址:"https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/"
几个常用提取信息工具的比较:
- 正则:很快,使用复杂,不用安装
- beautifulsoup:较慢,使用简单,安装简单
- lxml: 较快,使用简单,安装稍难
四大对象:
1.Tag
- 对应Html中的标签
- 可以通过soup.tag_name访问
- tag两个重要属性name和attrs
from urllib import request from bs4 import BeautifulSoup url = "http://www.baidu.com" rsp = request.urlopen(url) cnt = rsp.read() soup = BeautifulSoup(cnt, "lxml") cnt = soup.prettify() print(cnt) print("=="*10) print(soup.link) print(soup.link.name) print(soup.link.attrs) print(soup.link.attrs['type'])
2.NavigableString
- 对应内容值
3.BeautifulSoup
- 表示的是一个文档的内容,大部分可以把它当做tag对象
- 一般可以用soup来表示
4.Comment
- 特殊类型的NavagableString对象,对其输出,则内容不包括注释符号
遍历文档对象的方法:
- contents:返回tag子节点以列表的方式返回
- children:返回tag子节点以迭代器形式返回
- descendants:返回所有子孙节点
- string:返回所有字符类型
from urllib import request from bs4 import BeautifulSoup url = "http://www.baidu.com" rsp = request.urlopen(url) cnt = rsp.read() soup = BeautifulSoup(cnt, "lxml") for node in soup.head.contents: if node.name == 'meta': print(node) if node.name == 'title': print(node.string) #<meta content="text/html;charset=utf-8" http-equiv="content-type"/> #<meta content="IE=Edge" http-equiv="X-UA-Compatible"/> #<meta content="always" name="referrer"/> #<meta content="#2932e1" name="theme-color"/> #百度一下,你就知道
搜索文档对象的方法:
使用find_all(name, attrs, recursive, text, ** kwargs)
- name:按照字符串搜索,可以传入的内容为字符串,正则表达式,列表
- kwargs参数,用来表示属性
- text:对应tag的文本值
from urllib import request from bs4 import BeautifulSoup import re url = 'http://www.baidu.com' rsp = request.urlopen(url) content = rsp.read() soup = BeautifulSoup(content, 'lxml') tags = soup.find_all(re.compile('^me'), content="always") for tag in tags: print(tag) #<meta content="always" name="referrer"/>
CSS选择器的使用方法:
- 使用soup.select返回一个列表
- 通过标签名称: soup.select("title")
- 通过类名: soup.select(".content")
- id查找: soup.select("#name_id")
- 组合查找: soup.select("div #input_content")
- 属性查找: soup.select("img[class='photo'])
- 获取tag内容: tag.get_text
from urllib import request from bs4 import BeautifulSoup url = 'http://www.baidu.com' rsp = request.urlopen(url) content = rsp.read() soup = BeautifulSoup(content, 'lxml') titles = soup.select("title") print(titles[0]) print("==" * 12) metas = soup.select("meta[content='always']") print(metas[0]) #<title>百度一下,你就知道</title> #======================== #<meta content="always" name="referrer"/>