一、前言
前面几篇爬虫入门篇文章解析了如何使用requests模块向网站发送http请求,获取到网页的HTML数据。这篇我们来如何使用BeautifulSoup模块来从HTML文本中提取我们想要的数据。
二、定义
- Beautiful Soup,简称bs4,是Python的一个HTML或XML的解析库,一般用它来从网页中提取数据。
三、安装
pip install bs4
四、应用场景
- 在爬虫应用中,发起请求获得响应后,如果响应的内容是个html代码,并且html代码里有我们需要的数据,可以使用BeautifulSoup解析response返回的数据。
- 例如请求新浪热搜网址,返回热搜列表html代码。这是我们可以用BeautifulSoup提取标题列表、点击量列表等。
五、用法
demo_html = "<html>" \
"<head>" \
"<title>code_space</title>" \
"</head>" \
"<body>" \
"<a class='code_space'>Hello World</a>" \
"</body><html>"
from bs4 import BeautifulSoup
html_obj = BeautifulSoup(demo_html, 'html.parser', from_encoding='utf-8')
# 打印美化后到的html代码
print(html_obj.prettify())
# 打印html的title
print(html_obj.title.string)
# 获取指定标签里面的信息
print(html_obj.select(".code_space")[0].get_text())
六、测试demo
- 接下来我们根据前面几篇讲到的request发起GET请求的步骤,封装请求头,模拟请求“简书”官网的链接,采集我们要的信息。
import requests
from bs4 import BeautifulSoup
if __name__ == '__main__':
# 简书链接
url = "https://www.jianshu.com/"
cookie = "token=code_spaced"
header = {
"Cookie": cookie,
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Content-Type": "application/json",
"Host": "www.jianshu.com",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"
}
r2 = requests.get(url, headers=header, allow_redirects=False)
baidu_html = r2.text
html_obj = BeautifulSoup(baidu_html, 'html.parser', from_encoding='utf-8')
# 获取指定标签里面的信息
title_set = html_obj.select("a.title")
title_list = []
for title in title_set:
print("标签信息-->")
print(title)
title_list.append(title.get_text())
# 结合上篇文章提到的for循环快速打印序列内容的写法
print("收集到的标题有:")
print('\n--------------------\n'.join(n for n in title_list))
- 测试结果如下图: