【requests】【BeautifulSoup】获取页面简单信息

481 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1.Beautiful简介

简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据。 官方解释如下:

Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。 它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。 Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式 ,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明 一下原始编码方式就可以了。Beautiful Soup已成为和lxml、html6lib一样出色的python解释器, 为用户灵活地提供不同的解析策略或强劲的速度。

2.基本使用

from bs4 import BeautifulSoup

html = '''
<html><head><title>哈哈哈哈</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a 威威time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">你好</a>,
<a href="http://example.com/lacie" class="sister" id="link2">天是</a> and
<a href="http://example.com/tillie" class="sister" id="link3">草泥</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
'''
soup = BeautifulSoup(html,'lxml') # 创建BeautifulSoup对象

print(soup.prettify()) # 格式化输出 html格式

print(soup.title) # 打印标签中的所有内容

print(soup.title.name) # 获取标签对象的名字

print(soup.title.string) # 获取标签中的文本内容  == soup.title.text

print(soup.title.parent.name)  # 获取父级标签的名字

print(soup.p)  # 获取第一个p标签的内容

print(soup.p["class"])  # 获取第一个p标签的class属性

print(soup.a) # 获取第一个a标签

print(soup.find_all('a'))  # 获取所有的a标签

print(soup.find(id='link3')) # 获取id为link3的标签

print(soup.p.attrs) # 获取第一个p标签的所有属性

print(soup.p.attrs['class']) # 获取第一个p标签的class属性

print(soup.find_all('p',class_='title')) # 查找属性为title的p


#  通过下面代码可以分别获取所有的链接以及文字内容
for link in soup.find_all('a'):
    print(link.get('href')) # 获取链接

print(soup.get_text())# 获取所有文本

环境

IDE:Spyder

在这里插入图片描述

BeautifulSoup简单测试

import requests
from bs4 import BeautifulSoup
import re

r = requests.get("http://www.baidu.com")
r.encoding = "utf-8"
soup = BeautifulSoup(r.text,features="lxml")
#使用BeautifulSoup将网页内容解析页面内容

print(type(soup))
#查看soup类型

a = soup.find_all('a')
len(a)
#百度界面<a>标签的个数

soup.find_all('a')
#筛选以<a>标签开头的内容

soup.find_all('a',{'class':'lb'})
#筛选<a>标签中class="lb"的内容

soup.find_all('a',{'class':re.compile('lb')})
#使用re筛选<a>标签中class="lb"的内容

soup.find_all(string=re.compile('百度'))
#使用re筛选以“百度”为关键词的内容

做题

soup.find_all('head')
#打印head标签内容

soup.find_all('p')
#获取p标签的内容

soup.find_all('p',{'id':re.compile('cp')})
#获取<p>标签中id为cp的标签对象

print(soup.get_text())
#获取并打印HTML页面中的中文字符

Reference

BeautifulSoup库使用和参数---supreme999