前言

于是我就参考源码知道了 BeautifulSoup 这个库,然后仔细百度了这个库的安装和用法

正文

首先安装这个库

pip install BeautifulSoup4
# 需要下载 4
# 因为据说 3 已经停止更新了

1.首先得导入库

bs4 导入

from bs4 import BeautifulSoup

2.用BeautifulSoup 打开 html 代码

我们打开前面抓下来的代码,代码存在 html 变量里

soup = BeautifulSoup(html,'html.parser')

它还可以打开存在本地的HTML代码

soup = BeautifulSoup(open('index.html'),'html.parser')

具体参数功能等,可查看上面那个网页

3.提出我们想要的标签

BeautifulSoup 比直接用正则的其中一点好处在于,可以通过 Tag 来提取我们想要的内容

我通过以下代码得到了我想要的第一部分文字

# .p        代表 Tag 是 <p>
# .contents 属性可以将tag的子节点以列表的方式输出
#           我们可以用列表索引来获取它的某一个元素
# .string   用于去掉多余符号
msg = soup.p.contents[1].string + soup.p.contents[2].string

具体参数功能等,可查看上面那个网页

具体代码

具体代码如下:

def makeSoup(html):
    if html == '':
        return '抓不到数据了'
    else:
        # 用BeautifulSoup 打开 本地html代码,打开方式 html.parser
        # soup = BeautifulSoup(open('index.html'),'html.parser')

        soup = BeautifulSoup(html,'html.parser')

        # .p        代表 Tag 是 <p>
        # .contents 属性可以将tag的子节点以列表的方式输出
        #           我们可以用列表索引来获取它的某一个元素
        # .string   用于去掉多余符号
        msg = soup.p.contents[1].string + soup.p.contents[2].string

现在我得到了我想要的第一段文字,可是还不够,还需要有第二段才能实现我想要的功能


发表评论

电子邮件地址不会被公开。 必填项已用*标注