python爬虫入门篇:如何解析爬取到的网页数据?试下最简单的BeautifulSoup库!

一、前言

前面几篇爬虫入门篇文章解析了如何使用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))
  • 测试结果如下图:
    在这里插入图片描述
    在这里插入图片描述
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code_space

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值