Beautiful Soup 简明教程

Beautiful Soup - extract() Method

Method Description

Beautiful Soup 库中的 extract() 方法用于从文档树中移除标签或字符串。extract() 方法返回已移除的对象。它类似于 Python 列表中的 pop() 方法。

Syntax

extract(index)

Parameters

  1. Index − 要移除的元素的位置。缺省时为 None。

Return Type

extract() 方法返回已从文档树中移除的元素。

Example 1

html = '''
   <div>
      <p>Hello Python</p>
   </div>
'''
from bs4 import BeautifulSoup

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

tag1 = soup.find("div")
tag2 = tag1.find("p")
ret = tag2.extract()
print ('Extracted:',ret)
print ('original:',soup)

Output

Extracted: <p>Hello Python</p>
original:
<div>
</div>

Example 2

考虑以下 HTML 标记 -

<html>
   <body>
      <p> The quick, brown fox jumps over a lazy dog.</p>
      <p> DJs flock by when MTV ax quiz prog.</p>
      <p> Junk MTV quiz graced by fox whelps.</p>
      <p> Bawds jog, flick quartz, vex nymphs./p>
   </body>
</html>

以下为代码 -

from bs4 import BeautifulSoup

fp = open('index.html')
soup = BeautifulSoup(fp, 'html.parser')
tags = soup.find_all()
for tag in tags:
   obj = tag.extract()
   print ("Extracted:",obj)

print (soup)

Output

Extracted: <html>
<body>
<p> The quick, brown fox jumps over a lazy dog.</p>
<p> DJs flock by when MTV ax quiz prog.</p>
<p> Junk MTV quiz graced by fox whelps.</p>
<p> Bawds jog, flick quartz, vex nymphs.</p>
</body>
</html>
Extracted: <body>
<p> The quick, brown fox jumps over a lazy dog.</p>
<p> DJs flock by when MTV ax quiz prog.</p>
<p> Junk MTV quiz graced by fox whelps.</p>
<p> Bawds jog, flick quartz, vex nymphs.</p>
</body>
Extracted: <p> The quick, brown fox jumps over a lazy dog.</p>
Extracted: <p> DJs flock by when MTV ax quiz prog.</p>
Extracted: <p> Junk MTV quiz graced by fox whelps.</p>
Extracted: <p> Bawds jog, flick quartz, vex nymphs.</p>

Example 3

您还可以将 extract() 方法与 find_next()、find_previous() 方法和 next_element、previous_element 属性一起使用。

html = '''
<div>
<p><b>Hello</b><b>Python</b></p>
</div>
'''
from bs4 import BeautifulSoup

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

tag1 = soup.find("b")
ret = tag1.next_element.extract()
print ('Extracted:',ret)
print ('original:',soup)

Output

Extracted: Hello
original:
<div>
<p><b></b><b>Python</b></p>
</div>