爬虫bs4解析

目录

导入模块

源码

源码转换为BeautifulSoup对象

获取title标签

find 查找符合规则的第一个内容

find_all 查找所有符合规则的内容

string/get_text获取标签内容

获取带有属性的标签

css选择器

美化

爬取番组计划排行榜案例


爬虫四种解析:re 、xpath 、bs4、parsel

导入模块

from bs4 import BeautifulSoup

源码

html = '''<html>
    <head>
        <title>The Dormouse's story </title>
    </head>
    <body>
        <p class="title">The Dormouse's story</p>
        <p class="story">Once upon a time there were three little sisters; and their names were
        <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,
        <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>and
        <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; 
           and they lived at the bottom of a well.
     </p>
     <p class="story">...</p>
    </body>
</html>'''

源码转换为BeautifulSoup对象

#html源码,lxml解析器
soup = BeautifulSoup(html, 'lxml')

获取title标签

print(soup.title)

find 查找符合规则的第一个内容

print(soup.find('p'))

find_all 查找所有符合规则的内容

#如果内容里有标签也被提取
print(soup.find_all('p'))

string/get_text获取标签内容

仅find方法可提取文本信息

#只有find方法能提取文本信息
print(soup.find('p').string)
print(type(soup.find('p').string)) #返回bs4对象
print(soup.find('p').get_text())
print(type(soup.find('p').get_text())) #返回str类型

获取带有属性的标签

print(soup.find_all('p', attrs={'class': 'story'}))

print(soup.find_all('p', class_='story'))

css选择器

print(soup.select('a'))  #返回所有a标签

美化

print(soup.prettify())

爬取番组计划排行榜案例

import json
from bs4 import BeautifulSoup
import requests
url ='https://bgm.tv/anime/browser?sort=rank'
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
 }
req = requests.get(url,headers=headers)
req.encoding='utf-8'
#源码转换为bs4对象
html = BeautifulSoup(req.text,'lxml')
# 获取ul标签
list_ul = html.find('ul',attrs={'id':'browserItemList'})
# 获取ul标签中所有li标签
for data in list_ul.find_all('li'):
    # 中文名
    title = data.find('h3').find('a').get_text()
    # 外文名
    try:
        foreign_title = data.find('h3').find('small').get_text()
    except:
        foreign_title = ""

    message = data.find('p').get_text().strip().split("/")
    # 年份
    year = message[1]
    #集数(话)
    hua = message[0]
    # 作者
    distortionist = message[2:]
    #评分
    score = data.find('div',class_='inner').find('p',class_='rateInfo').find('small',class_='fade').get_text()
    #存入字典
    cartoon_dict = {
        '中文名': title,
        '外文名': foreign_title,
        '年份': year,
        '话': hua,
        '作家': distortionist,
        '评分': score,
    }
    # json格式写入text
    with open('./番组计划排行榜.txt','a',encoding='utf8') as f1:
        f1.write(json.dumps(cartoon_dict,ensure_ascii=False,indent=4)+'\n')

2-3个中文字符:[^\u4E00-\u9FA5]{2,3}

您好!对于Python爬虫,使用BeautifulSoup (通常简写为bs4)是一个常见的选择。BeautifulSoup是一个解析HTML和XML文档的Python库,它提供了简单又灵活的方式来遍历和搜索文档树。 要使用BeautifulSoup,您需要在Python环境中安装该库。可以使用pip命令来安装: ``` pip install beautifulsoup4 ``` 安装完成后,您可以开始编写爬虫代码。首先,您需要导入BeautifulSoup模块和相应的库,例如requests用于发送HTTP请求: ```python from bs4 import BeautifulSoup import requests ``` 然后,您可以使用requests库发送HTTP请求获取页面内容,并将其传递给BeautifulSoup进行解析: ```python url = 'https://www.example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') ``` 在这个例子中,我们使用requests库发送GET请求来获取https://www.example.com网页的内容。然后,我们将返回的内容传递给BeautifulSoup构造函数进行解析,并指定解析器为'html.parser'。 接下来,您可以使用BeautifulSoup提供的方法来遍历和搜索文档树,以提取所需的数据。例如,您可以使用find()或find_all()方法来查找特定的元素或标签: ```python # 查找第一个<div>标签 tag = soup.find('div') # 查找所有<a>标签 tags = soup.find_all('a') ``` 这只是Python爬虫使用BeautifulSoup的基本操作示例。您可以根据需要进一步学习和探索BeautifulSoup的功能以及其他相关库。 希望这能帮到您!如果您有更多问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值