安装
pip install beautifulsoup4
卸载:
pip uninstall beautifulsoup4
## import
import requests
import os
from bs4 import BeautifulSoup
import bs4
import re
demo
r = requests.get("网址")
r.encoding = r.apparent_encoding
demo = r.text
soup = BeautifulSoup(demo, 'html.parser')
res = list()
for item in soup.find_all('a', string=re.compile('疫')):
res.append(item.string)
print(res)
上面可以简单的看作一段代码,大致意思就是在网页上寻找中含有“疫”的内容。
具体的用法会在后面给出。
Beautifulsoup操作
首先我们先明确html的基本结构
是很明显的树状结构。
基本元素
查看标签a的属性
输入: tag=soup.a
tag.attrs
查看标签a的属性中class的值
输入:tag.attrs['class']
查看标签a的属性 的类型
输入:type(tag.attrs)
遍历
注:.contents 和 .children 属性仅包含tag的直接子节点,.descendants 属性可以对所有tag的子孙节点进行递归循环,和 children类似,我们也需要遍历获取其中的内容。
·标签树的下行遍历
获得孩子节点的个数
len(soup.body.contents)
分别输出各个子节点
soup.body.contents[2]
·标签树的上行遍历
获得a节点的父节点名称
soup.a.parent.name
获得a节点的所有先辈点名称
for parent in soup.a.parents:
print(parent.name)
注:遍历所有先辈节点,包括soup本身
·标签树的平行遍历
获得a节点的上一个节点和下一个节点
soup.a.next_sibling
soup.a.previous_sibling
## bs4库的prettify()方法
.prettify()为HTML文本<>及其内容增加换行符可以用于整个HTML文本,也可以用于单个标签方法:
.prettify()
注:bs4库将任何HTML输入都变成utf‐8编码Python 3.x默认支持编码是utf‐8,解析无障碍
## 信息检索
import requests
r=requests.get("http://www.baidu.com/")
r.encoding=r.apparent_encoding
demo=r.text
from bs4 import BeautifulSoup
soup=BeautifulSoup(demo, 'html.parser')
print(soup.find_all('a'))
<>.find_all(name,attrs,recursive,string,**kwargs)
name: 对标签名称的检索字符串
attrs: 对标签属性值的检索字符串,可标注属性检索
recursive: 是否对子孙全部检索,默认True
string: <>…</>中字符串区域的检索字符串
扩展方法:
实战爬取
爬取百度热门人物排行
# 2.2
r = requests.get('http://top.baidu.com/buzz?b=257&c=9&fr=topcategory_c9')
r.encoding = r.apparent_encoding
demo2 = r.text
soup2 = BeautifulSoup(demo2, 'html.parser')
res2 = list()
for i in soup2.find_all('a', 'list-title'):
res2.append(i.string)
for index,i in enumerate(res2):
print(index,i)
大学排名爬取
# 2.3
url3 = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html'
r = requests.get(url3)
r.encoding = r.apparent_encoding
demo3 = r.text
soup3 = BeautifulSoup(demo3, 'html.parser')
res3 = list()
for item in soup3.find('tbody').children:
tmp = list()
if isinstance(item, bs4.element.Tag):
tdList = item('td')
tmp.append(tdList[0].string)
tmp.append(tdList[1].string)
tmp.append(tdList[3].string)
res3.append(tmp)
注:
定义的输出格式模板变量,^代表居中,4/12/10代表输出宽度(当输出数据超过该数字时,以实际输出为准),{3}代表打印输出时,我们使用format中的第3个变量(由0起始),也就是 chr(12288)
chr(12288)代表全角Unicode空格(即中文空格)