BeautifulSoup库的使用

BeautifulSoup库的使用

1 解析库

解析器使用方法优势劣势
Python标准库BeautifulSoup(markup, "html.parser")Python的内置标准库、执行速度适中 、文档容错能力强Python 2.7.3 or 3.2.2)前的版本中文容错能力差
lxml HTML 解析器BeautifulSoup(markup, "lxml")速度快、文档容错能力强需要安装C语言库
lxml XML 解析器BeautifulSoup(markup, "xml")速度快、唯一支持XML的解析器需要安装C语言库
html5libBeautifulSoup(markup, "html5lib")最好的容错性、以浏览器的方式解析文档、生成HTML5格式的文档速度慢、不依赖外部扩展

2 标签选择器

2.1 获取元素

from bs4 import BeautifulSoup

html = """
<html>
    <head>
        <title>The Dormouse's story</title>
    </head>
<body><p class="story" name = "liming">...
"""
soup = BeautifulSoup(html, 'lxml')
print(soup.title)           # <title>The Dormouse's story</title>
print(soup.head)            # <head><title>The Dormouse's story</title></head>

有多个并列标签时,返回第一个;有多个嵌套标签时,返回最外的一个。

print(soup.prettify()) #返回补全标签后的html

2.2 获取名称

print(soup.p.name)          # p
print(soup.title.name)      # title

2.3 获取属性

print(soup.p.attrs['name']) # liming
print(soup.p['name'])       # liming

2.4 获取内容

print(soup.title.string)    # The Dormouse's story

2.5 嵌套选择

print(soup.html.head.title.string)       # The Dormouse's story

2.6 子/后代节点

html = """
<html>
    <head>
        <title>The Dormouse's story</title>
    </head>
    <body>
        <p class="story">
            Once upon a time
            <a>
                <span>Elsie</span>
            </a>
            <a>Lacie</a> 
            and
            <a>Tillie</a>
            the bottom of a well.
        </p>
        <p class="story">...</p>
"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')

(1)子节点(2种)

print(type(soup.p.contents))
print(soup.p.contents)

输出:

<class 'list'>
['\n            Once upon a time\n            ', <a>
<span>Elsie</span>
</a>, '\n', <a>Lacie</a>, ' \n            and\n            ', <a>Tillie</a>, '\n            the bottom of a well.\n        ']

print(soup.p.children)
print(list(enumerate(soup.p.children)))

输出:

<list_iterator object at 0x0000020BC17BEBA8>
[(0, '\n            Once upon a time\n            '), (1, <a>
<span>Elsie</span>
</a>), (2, '\n'), (3, <a>Lacie</a>), (4, ' \n            and\n            '), (5, <a>Tillie</a>), (6, '\n            the bottom of a well.\n        ')]

(2)后代节点

print(soup.p.descendants)           
for i, child in enumerate(soup.p.descendants):
    print(i, child)

输出:

<generator object descendants at 0x000001B746B0ADB0>
0 
            Once upon a time

1 <a>
<span>Elsie</span>
</a>
2 

3 <span>Elsie</span>
4 Elsie
5 

6 

7 <a>Lacie</a>
8 Lacie
9  
            and

10 <a>Tillie</a>
11 Tillie
12 
            the bottom of a well.

2.7 兄弟节点

print(list(enumerate(soup.a.previous_siblings)))        # [(0, '\n            Once upon a time\n            ')]
print(list(enumerate(soup.a.next_siblings)))            # [(0, '\n'), (1, <a>Lacie</a>), (2, ' \n            and\n            '), (3, <a>Tillie</a>), (4, '\n            the bottom of a well.\n        ')]

2.8 父/祖先节点

html = '<html><head><title>The Dormouses story'

from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')

print(soup.title.parent)                # <head><title>The Dormouses story</title></head>

print(list(enumerate(soup.title.parents)))  

# [(0, <head><title>The Dormouses story</title></head>), 
# (1, <html><head><title>The Dormouses story</title></head></html>), 
# (2, <html><head><title>The Dormouses story</title></head></html>)]

3 标准选择器

方法描述方法描述
find()返回第一个元素find_all()返回所有元素
find_parents()返回所有祖先节点find_parent()返回直接父节点。
find_next_siblings()返回后面所有兄弟节点find_next_sibling()返回后面第一个兄弟节点
find_previous_siblings()返回前面所有兄弟节点find_previous_sibling()返回前面第一个兄弟节点。
find_all_next()返回节点后所有符合条件的节点find_next()返回第一个符合条件的节点
find_all_previous()返回节点后所有符合条件的节点find_previous()返回第一个符合条件的节点

以find_all为例获取标签

find_all ( name , attrs , recursive , text , **kwargs ),可根据标签名、属性、内容查找文档。

html='''
    <div class="panel-body">
        <ul class="list" id="1"><li>Foo</li><li>Map</li></ul>
        <ul name="Mike"><li>Bar</li></ul>
    </div>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')

(1)根据name

print(soup.find_all('ul'))      # [<ul class="list" id="1"><li>Foo</li><li>Map</li></ul>, <ul name="Mike"><li>Bar</li></ul>]

for ul in soup.find_all('ul'):
    print(ul.find_all('li'))

# [<li>Foo</li>, <li>Map</li>]
# [<li>Bar</li>]

(2)根据attrs

print(soup.find_all(attrs={'id': '1'}))     # [<ul class="list" id="1"><li>Foo</li><li>Map</li></ul>]

(3)获取text

print(soup.find_all(text='Foo'))            # ['Foo']

4 CSS选择器

通过select()直接传入CSS选择器即可完成选择

html='''
<div class="1">
    <div id="2">
        <li name="Mike">Hello</li>
        <li>Goodbye</li>
    </div>
</div>
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')

4.1 获取标签

print(type(soup.select('.1 #2 li')))        # <class 'list'>
# 有空格隔开, .代表class, #代表id  ,select获取所有元素
print(soup.select('.1 #2 li'))              # [<li name="Mike">Hello</li>, <li>Goodbye</li>]
print(soup.select('li')[0])                 # <li name="Mike">Hello</li>
print(soup.select('li')[1])                 # <li>Goodbye</li>

4.2 获取属性

print(soup.select('li')[0].attrs['name'])   # Mike
print(soup.select('li')[0]['name'])         # Mike

4.3 获取内容

print(soup.select('li')[0].get_text())      # Hello

总结

  • 推荐使用lxml解析库,必要时使用html.parser
  • 标签选择筛选功能弱但是速度快
  • 建议使用find()、find_all() 查询匹配单个结果或者多个结果
  • 如果对CSS选择器熟悉建议使用select()
  • 记住常用的获取属性和文本值的方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
BeautifulSoup是一个Python的HTML/XML解析,可以用来从HTML或XML文件中提取数据。它的使用非常简单,以下是使用BeautifulSoup的基本步骤: 1. 安装BeautifulSoup使用pip命令安装BeautifulSoup,如:pip install beautifulsoup4。 2. 导入:在Python脚本中导入BeautifulSoup,如:from bs4 import BeautifulSoup。 3. 获取HTML/XML文档:使用requests等获取网页的HTML代码,或者从本地文件中读取HTML/XML文档。 4. 创建BeautifulSoup对象:使用BeautifulSoup类创建一个BeautifulSoup对象,并传入HTML/XML文档和解析器(一般使用默认解析器)。 5. 解析文档:使用BeautifulSoup对象的方法,如find、find_all等,对文档进行解析,提取所需的数据。 6. 处理数据:对提取的数据进行处理和清洗,如去除空格、换行符等。 7. 存储数据:将获取的数据存储到本地文件或数据中,便于后续分析和使用。 下面是一个简单的示例代码,演示如何使用BeautifulSoup提取网页中的所有超链接: ```python import requests from bs4 import BeautifulSoup url = 'http://www.example.com/' r = requests.get(url) html_doc = r.text soup = BeautifulSoup(html_doc, 'html.parser') links = [] for link in soup.find_all('a'): links.append(link.get('href')) print(links) ``` 在这个示例代码中,首先使用requests获取了http://www.example.com/网页的HTML代码,然后使用BeautifulSoup解析该网页,并提取了所有超链接,并将它们存储在一个列表中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值