python进阶-02-一篇文章搞明白BeautifulSoup

python进阶-02-一篇文章搞明白BeautifulSoup

一.说明

开始今天的日拱一卒,上一篇文章我们介绍了Xpath,今天我们开始介绍BeautifulSoup,这个也是用来解析HTML文档的技术,但是跟Xpath 还是有区别的,XPath 是使用路径表达式来定位元素,而BeautifulSoup就是一个字简单。

二.安装

要使用BeautifulSoup,就的先安装,但是BeautifulSoup的安装方式跟之前不一样,因为BeautifulSoup 已经被zhenghe到bs4 中了故需要安装 bs4

pip install bs4 -i http://pypi.doubanio.com/simple --trusted-host pypi.doubanio.com

三.创建 BeautifulSoup 对象

   response = requests.get('https://www.iciba.com/word',params=params.dict())
   html = response.content.decode('utf-8', 'ignore')  # 'ignore' 忽略非法字符[starts-with(@id,"b")]
   # 创建 BeautifulSoup 对象
   soup = BeautifulSoup(html, 'html.parser')

四.BeautifulSoup 的解析器

刚刚我们通过soup = BeautifulSoup(html, ‘html.parser’) 来解析html文档来实现创建 BeautifulSoup 对象

‘html.parser’ 就是BeautifulSoup 的解析器,以下为BeautifulSoup支持的解析器

解析器调用方法
Python标准库BeautifulSoup(html,“html.parser”)
lxml HTML 解析器BeautifulSoup(html, “lxml”)需要安装c语言库
lxml XML 解析器BeautifulSoup(xml_content, [“lxml-xml”])BeautifulSoup(xml_content, “xml”)需要安装c语言库
html5lib 解析器BeautifulSoup(html, “html5lib”)

五.BeautifulSoup 基本语法

  1. 获取整个文档的结构:print(soup.prettify())

  2. 基础用法:

    操作描述
    soup.title获取整个 <title> 标签字段
    soup.title.name获取 <title> 标签的名称(即 “title”)
    soup.title.parent.name获取 <title> 标签的父级标签名称
    soup.p获取第一个 <p> 标签
    soup.p['class']获取第一个 <p> 标签中的 class 属性值
    soup.p.get('class')soup.p['class'] 等价,返回 class 属性值
    soup.a获取第一个 <a> 标签
    soup.find_all('a')获取所有 <a> 标签
    soup.find(id="link3")获取 id="link3" 的标签
    soup.a['class'] = "newClass"修改第一个 <a> 标签的 class 属性值
    del soup.a['class']删除第一个 <a> 标签的 class 属性
    soup.find('a').get('id')获取第一个 <a> 标签的 id 属性值
    soup.title.string获取 <title> 标签的文本内容
    soup.title.stripped_strings去掉空格换行等
    soup.get_text()获取标签及子标签包含的文本内容
  3. 查找标签:soup.find()soup.find_all()

    # 查找第一个 <h1> 标签
    h1_tag = soup.find('h1')
    print(h1_tag.text)  # 打印出 h1 标签中的文本内容
    
    # 查找所有的 <a> 标签
    a_tags = soup.find_all('a')
    for tag in a_tags:
        print(tag.get('href'))  # 打印出所有链接的 href 属性
        
        
    # 查找类名为 "example" 的 <div> 标签
    div_tag = soup.find('div', class_='example')
    print(div_tag.text)
    
    # 查找 ID 为 "main" 的 <div> 标签
    main_div = soup.find(id='main')
    print(main_div.text)
    
  4. CSS 选择器查找标签:使用 select() 方法来查找符合条件的元素

    # 查找所有 class 为 "item" 的 <div> 标签
    items = soup.select('div.item')
    for item in items:
        print(item.text)
    

六.BeautifulSoup 和正则表达式匹配

from bs4 import BeautifulSoup
import re

# 假设 `html` 是你的 HTML 内容
html = '''<html>
            <div class="Mean_trans1"><p>Text 1</p></div>
            <div class="Mean_trans2"><p>Text 2</p></div>
            <div class="Mean_trans3"><p>Text 3</p></div>
          </html>'''

# 创建 BeautifulSoup 对象
soup = BeautifulSoup(html, 'html.parser')

# 使用正则表达式匹配 class 属性以 'Mean_trans' 开头的 div 标签
div = soup.find('div', class_=re.compile('^Mean_trans'))

# 获取第一个 <p> 标签的文本内容
text = div.find('p').text if div else None

print(text)

七.实战,用来技术交流,需要翻译请购买对应API

    response = requests.get('https://www.iciba.com/word',params={'w':'Hello World'})
    html = response.content.decode('utf-8', 'ignore')  # 'ignore' 忽略非法字符[starts-with(@id,"b")]
    # 创建 BeautifulSoup 对象
    soup = BeautifulSoup(html, 'html.parser')
    result="无数据"
    try:
        
        divs = soup.find('ul', class_=re.compile('^Mean_part'))
        print(divs)
        # 提取每个 div 中的第一个 <p> 标签的文本内容
        texts = divs.find('span').text
        result = texts
    except Exception as e:
        print(e)
    return result

八.总结

Python 进阶中的BeautifulSoup是不是超级简单,比Xpath 还要简单不少!

创作整理不易,请大家多多关注 多多点赞,有写的不对的地方欢迎大家补充,我来整理,再次感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

SEEONTIME

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

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

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

打赏作者

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

抵扣说明:

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

余额充值