bs4模块

bs4模块与案例

使用指南

bs4,全称BeautifulSoup 4,是Python中一个强大的网页解析库,它可以帮助我们方便地从网页中提取数据。bs4将复杂HTML文档转换成树形结构,每个节点都是Python对象,所有对象可以归纳为4种:Tag,NavigableString,BeautifulSoup,Comment。

安装bs4

在Python环境下,我们可以使用pip命令进行安装:

pip install beautifulsoup4

基本使用

1)导入bs4库

from bs4 import BeautifulSoup

2)创建BeautifulSoup对象

我们可以使用以下方式创建一个BeautifulSoup对象:

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

这里,'html_doc’是HTML文档字符串,'html.parser’是解析器。

3)访问标签

我们可以使用soup.tag_name访问HTML中的标签。例如:

print(soup.title)

输出:

The Dormouse's story

4)获取标签的属性

我们可以使用tag[‘attr’]或者tag.get(‘attr’)来获取标签的属性。例如:

print(soup.a['href'])

输出:

http://example.com/elsie

5)获取标签的内容

我们可以使用tag.string或者tag.text来获取标签的内容。例如:

print(soup.title.string)

输出:

The Dormouse's story

搜索文档树

bs4提供了多种方法来搜索文档树,例如.find_all(),.find()等。

例如:

html_doc = """
The Dormouse's story

The Dormouse's story

"""
soup = BeautifulSoup(html_doc, 'html.parser') title_tag = soup.find_all('title') print(title_tag)

输出:

[<title>The Dormouse's story</title>]

网易云音乐案例

获取并解析流行歌曲标题:

bs4模块_第1张图片

import requests
from bs4 import BeautifulSoup

response = requests.get(
    url = "https://music.163.com/discover/playlist/?cat=%E6%B5%81%E8%A1%8C",
    headers = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
        "Referer":"https://music.163.com/"
    }
)
soup = BeautifulSoup(response.text,features="html.parser")
tag = soup.find(name="ul" , attrs={"id" : "m-pl-container"}) # 定位到ul标签
for li in tag.find_all(recursive=False):  # 遍历所有li标签,不进行递归遍历
    a = li.find(name = "a",attrs = {"class":"msk"}) # 获取a标签
    print(a.attrs['title']) # 通过attrs拿到标题属性 也可直接使用a['title']来获取标题

结果:

bs4模块_第2张图片

你可能感兴趣的:(python爬虫,python,爬虫,网络爬虫)