天天看点

BeautifulSoup库用法总结

0.写在前面

在python的爬虫中,经常需要用到强大的beautifulsoup库,如之前写的

股票数据的爬取

中就用到了它。在这里,将详细总结beautifulsoup的用法,来巩固相关知识。以下便是我从各种网站搜集的资料,在这里做一个汇总。(我从不生产知识,我只是知识的搬运工)

1.基本介绍

BeautifulSoup库用法总结

beautifulsoup

2.安装/引用

安装:win平台中‘以管理员身份运行’cmd,执行

pip install beautifulsoup4

即可安装

引用:

from bs4 import BeautifulSoup

import bs4

即可

3.使用方法

BeautifulSoup库用法总结

先煲制一锅汤

BeautifulSoup库用法总结

解析器

BeautifulSoup库用法总结

基本元素

BeautifulSoup库用法总结

对应各元素

BeautifulSoup库用法总结

一个用于接下来分析的demo

BeautifulSoup库用法总结

tag标签

BeautifulSoup库用法总结

tag.name

BeautifulSoup库用法总结

attrs

BeautifulSoup库用法总结

string

BeautifulSoup库用法总结

comment

如果不想输出内容的注释,可以写一个if语句:
if type(newsoup.b.string)==element.Comment:
    print (newsoup.b.string)
           
bs4库将任何HTML输入都变成utf-8编码,python3.x默认支持编码是utf-8编码,解析无障碍
BeautifulSoup库用法总结

beautifulsoup库基本入门

BeautifulSoup库用法总结

HTML基本格式

BeautifulSoup库用法总结

标签树的下行遍历

BeautifulSoup库用法总结

标签树的上行遍历

BeautifulSoup库用法总结

标签树的平行遍历

本文参考

中国大学MOOC

/

kikaylee的专栏

继续阅读