0.写在前面
在python的爬虫中,经常需要用到强大的beautifulsoup库,如之前写的股票数据的爬取中就用到了它。在这里,将详细总结beautifulsoup的用法,来巩固相关知识。以下便是我从各种网站搜集的资料,在这里做一个汇总。(我从不生产知识,我只是知识的搬运工)
1.基本介绍
![img_50c5aed161c7a7c8bcd45de12e3659f9.png](https://yqfile.alicdn.com/img_50c5aed161c7a7c8bcd45de12e3659f9.png)
beautifulsoup
2.安装/引用
安装:win平台中‘以管理员身份运行’cmd,执行pip install beautifulsoup4
即可安装
引用:from bs4 import BeautifulSoup
或import bs4
即可
3.使用方法
![img_a9e892fe7990c5bd0d3ba543b2694d66.png](https://yqfile.alicdn.com/img_a9e892fe7990c5bd0d3ba543b2694d66.png)
先煲制一锅汤
![img_c9a49023529b9a44da992ead43a0c897.png](https://yqfile.alicdn.com/img_c9a49023529b9a44da992ead43a0c897.png)
解析器
![img_87d47e8b6274f0a603f9e2019cedb4a6.png](https://yqfile.alicdn.com/img_87d47e8b6274f0a603f9e2019cedb4a6.png)
基本元素
![img_0cb2809155acda65b06bac86201798c2.png](https://yqfile.alicdn.com/img_0cb2809155acda65b06bac86201798c2.png)
对应各元素
![img_04ed223ff98fb02880218ced2b1b0cd4.png](https://yqfile.alicdn.com/img_04ed223ff98fb02880218ced2b1b0cd4.png)
一个用于接下来分析的demo
![img_70b0e58e902eb7170b49737676e58978.png](https://yqfile.alicdn.com/img_70b0e58e902eb7170b49737676e58978.png)
tag标签
![img_84bd13768c34d9a4df42ed543038b661.png](https://yqfile.alicdn.com/img_84bd13768c34d9a4df42ed543038b661.png)
tag.name
![img_f7b2971b8785da3ae7314c48bd4c4c3b.png](https://yqfile.alicdn.com/img_f7b2971b8785da3ae7314c48bd4c4c3b.png)
attrs
![img_af450964effdd8b033f0322933d643c3.png](https://yqfile.alicdn.com/img_af450964effdd8b033f0322933d643c3.png)
string
![img_db18eb4c2307a635d60ac3e5c7140d00.png](https://yqfile.alicdn.com/img_db18eb4c2307a635d60ac3e5c7140d00.png)
comment
如果不想输出内容的注释,可以写一个if语句:
if type(newsoup.b.string)==element.Comment:
print (newsoup.b.string)
bs4库将任何HTML输入都变成utf-8编码,python3.x默认支持编码是utf-8编码,解析无障碍
![img_f2b679ac340a60f10157641b47b7aed4.png](https://yqfile.alicdn.com/img_f2b679ac340a60f10157641b47b7aed4.png)
beautifulsoup库基本入门
![img_00af021a65ac1621b39bc70e72ced0cb.png](https://yqfile.alicdn.com/img_00af021a65ac1621b39bc70e72ced0cb.png)
HTML基本格式
![img_2fcbf62276e9bc4a71da17cbe1913626.png](https://yqfile.alicdn.com/img_2fcbf62276e9bc4a71da17cbe1913626.png)
标签树的下行遍历
![img_914afd0ccd81c9fc77e105d5cb6ee87a.png](https://yqfile.alicdn.com/img_914afd0ccd81c9fc77e105d5cb6ee87a.png)
标签树的上行遍历
![img_2af4f37c6d9b53762521380340472a1e.png](https://yqfile.alicdn.com/img_2af4f37c6d9b53762521380340472a1e.png)
标签树的平行遍历
本文参考中国大学MOOC / kikaylee的专栏