1、安装:
pip install beautifulsoup4
二、可选择安装解析器:
pip install lxml
pip install html5lib
三、解析器比较:
解析器 |
使用方法 |
优点 |
劣势 |
Python标准库 |
BeautifulSoup(markup, "html.parser") |
- Python的内置标准库
- 执行速度适中
- 文档容错能力强
|
- Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差
|
lxml HTML 解析器 |
BeautifulSoup(markup, "lxml") |
|
|
lxml XML 解析器 |
BeautifulSoup(markup, ["lxml", "xml"])html BeautifulSoup(markup, "xml")html5 |
|
|
html5lib |
BeautifulSoup(markup, "html5lib") |
- 最好的容错性
- 以浏览器的方式解析文档
- 生成HTML5格式的文档
|
|
|
|
|
|
from bs4 import BeautifulSoupimport requests,rereq_obj = requests.get('https://www.baidu.com')soup = BeautifulSoup(req_obj.text,'lxml')'''标签查找'''print(soup.title) #只是查找出第一个print(soup.find('title')) #效果和上面同样print(soup.find_all('div')) #查出全部的div标签'''获取标签里的属性'''tag = soup.divprint(tag['class']) #多属性的话,会返回一个列表print(tag['id']) #查找标签的id属性print(tag.attrs) #查找标签全部的属性,返回一个字典(属性名:属性值)'''标签包的字符串'''tag = soup.titleprint(tag.string) #获取标签里的字符串tag.string.replace_with("哈哈") #字符串不能直接编辑,能够替换'''子节点的操做'''tag = soup.headprint(tag.title) #获取head标签后再获取它包含的子标签'''contents 和 .children'''tag = soup.bodyprint(tag.contents) #将标签的子节点以列表返回print([child for child in tag.children]) #输出和上面同样'''descendants'''tag = soup.body[print(child_tag) for child_tag in tag.descendants] #获取全部子节点和子子节点'''strings和.stripped_strings'''tag = soup.body[print(str) for str in tag.strings] #输出全部全部文本内容[print(str) for str in tag.stripped_strings] #输出全部全部文本内容,去除空格或空行'''.parent和.parents'''tag = soup.titleprint(tag.parent) #输出便签的父标签[print(parent) for parent in tag.parents] #输出全部的父标签'''.next_siblings 和 .previous_siblings 查出全部的兄弟节点''''''.next_element 和 .previous_element 下一个兄弟节点''''''find_all的keyword 参数'''soup.find_all(id='link2') #查找全部包含 id 属性的标签soup.find_all(href=re.compile("elsie")) #href 参数,Beautiful Soup会搜索每一个标签的href属性:soup.find_all(id=True) #找出全部的有id属性的标签soup.find_all(href=re.compile("elsie"), id='link1') #也能够组合查找soup.find_all(attrs={"属性名": "属性值"}) #也能够经过字典的方式查找