爬虫BeautifulSoup功能(上)

BeautifulSoup模块介绍

BeautifulSoup是一个可以从html或xml文件中提取数据的python库。

BeautifulSoup安装:

可以直接在pycharm中terminal直接输入pip install BeautifulSoup4或者在File->settings->project interpreter->按+号搜索添加bs4。

代码

#1.Tag 标签及其内容,拿到它找到的第一个内容
#bs.a.attrs获取a标签所有属性,返回一个字典获取a标签的所有属性
#3去注释

from bs4 import BeautifulSoup
import re

file = open("./baidu.html","rb")
html = file.read()
bs = BeautifulSoup(html,"html.parser")
print(bs.title) #1.Tag 标签及其内容,拿到它找到的第一个内容

print(bs.div.attrs) #bs.a.attrs获取a标签所有属性,返回一个字典获取a标签的所有属性

print(bs.a.string) #去注释

运行结果

在这里插入图片描述

分析:

该串代码通过爬取的百度代码来分析BeautifulSoupD的一些功能分别为
1.Tag 标签及其内容,拿到它找到的第一个内容
2.bs.a.attrs获取a标签所有属性,返回一个字典获取a标签的所有属性
3.去注释
代码可以直接复制pycharm中但自己需要提前在同目录下建一个爬取的百度html文档在用该代码来实现。

猜你喜欢

转载自blog.csdn.net/weixin_48106407/article/details/107622446