【Beautiful Soup库】{0} ——Beautiful Soup库的简介

首先我们安装一下 Beautiful Soup库:

以管理员身份运行命令提示符,输入pip install beautifulsoup4


Beautiful Soup库简介:

Beautiful Soup库能够对HTML、XML格式进行解析,并且提取其中的相关信息。

Beautiful Soup库可以对你提供给它的任何格式进行相关的爬取,并且可以进行树形解析。

Beautiful Soup库使用原理:把我们给它的文档当作一锅汤,然后煲制这锅汤。


Beautiful Soup库小测:

演示HTML页面地址:http://python123.io/ws/demo.html

如何获得页面源代码?

一、手工获得,在浏览器打开页面,查看源代码。
在这里插入图片描述

二、用 requests库来自动获得链接对应的源代码。

import requests
r = requests.get("https://python123.io/ws/demo.html")
print(r.text)

Output:


获得源代码后,我们用Beautiful Soup库进行解析:

import requests
from bs4 import BeautifulSoup

r = requests.get("https://python123.io/ws/demo.html")
demo = r.text
soup = BeautifulSoup(demo, "html.parser")
print(soup.prettify())

Output:

<html>
 <head>
  <title>
   This is a python demo page
  </title>
 </head>
 <body>
  <p class="title">
   <b>
    The demo python introduces several python courses.
   </b>
  </p>
  <p class="course">
   Python is a wonderful general-purpose programming language. You can learn Python from novice to professional by tracking the following courses:
   <a class="py1" href="http://www.icourse163.org/course/BIT-268001" id="link1">
    Basic Python
   </a>
   and
   <a class="py2" href="http://www.icourse163.org/course/BIT-1001870001" id="link2">
    Advanced Python
   </a>
   .
  </p>
 </body>
</html>

这说明 BeautifulSoup库成功解析了我们给出的demo页面。


怎么使用Beautiful Soup库呢?

from bs4 import BeautifulSoup
soup = BeautifulSoup('<p>data</p>', 'html.parser')

BeautifulSoup 是一个类
第一个参数是我们需要 BeautifulSoup 解析的一个 html 格式的信息
html.parser 是解析器


参考资料:Python网络爬虫与信息提取(北京理工大学慕课)

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值