Python Beautiful Soup 4 (BS4) 库使用技巧

Python Beautiful Soup 4 (BS4) 库使用技巧

技术教程gslnedu2025-05-21 13:40:574A+A-

Beautiful Soup 4 (BS4) 是一个非常灵活和强大的库,有很多使用技巧可以让你的HTML解析工作更高效和简洁。这里列举一些:


1. 使用更精确的选择器 (CSS Selectors):


select() 和 select_one() 方法允许你使用CSS选择器,这通常比 find() 和 find_all() 结合多种参数更直观和强大。


from bs4 import BeautifulSoup


html_doc = """

<html><body>

<div id="main">

<h1 class="title">Hello World</h1>

<p class="content">First paragraph.</p>

<ul class="list">

<li>Item 1</li>

<li class="special">Item 2</li>

<li>Item 3</li>

</ul>

<a href="/next" class="nav next-link">Next</a>

</div>

<div class="sidebar">

<p>Sidebar content</p>

</div>

</body></html>

"""

soup = BeautifulSoup(html_doc, 'lxml')


# 选择ID为main的元素

main_div = soup.select_one('#main')

print(f"Main div: {main_div.name if main_div else 'Not found'}")


# 选择所有class为content的p标签

content_paragraphs = soup.select('p.content')

for p in content_paragraphs:

print(f"Content p: {p.get_text()}")


# 选择ul下所有class为special的li标签 (后代选择器)

special_item = soup.select_one('ul li.special') # 或者 'ul.list li.special'

print(f"Special item: {special_item.get_text() if special_item else 'Not found'}")


# 选择具有href属性且class包含nav的a标签 (属性选择器和部分类名匹配)

next_link = soup.select_one('a[href].nav') # .nav 意味着 class="nav" 或 class="nav something"

print(f"Next link href: {next_link['href'] if next_link else 'Not found'}")


# 选择 #main 下直接子元素中的 h1

h1_direct_child = soup.select_one('#main > h1.title')

print(f"Direct H1: {h1_direct_child.get_text() if h1_direct_child else 'Not found'}")


2. 灵活的 find_all() 参数:


传入列表: 查找多种标签。

python headings = soup.find_all(['h1', 'h2', 'h3'])


传入正则表达式: 匹配标签名或属性值。

python import re # 查找所有以 "b" 开头的标签 (e.g., <body>, <br>, <b>) b_tags = soup.find_all(re.compile("^b")) # 查找所有href属性包含 "image" 的链接 image_links = soup.find_all('a', href=re.compile("image"))


传入函数 (lambda 或 def): 进行复杂的自定义匹配。

```python

# 查找所有有 "class" 属性但没有 "id" 属性的div

def has_class_but_no_id(tag):

return tag.name == 'div' and tag.has_attr('class') and not tag.has_attr('id')

divs = soup.find_all(has_class_but_no_id)


# 查找文本内容为 "Item 2" 的标签

item2 = soup.find_all(text="Item 2") # 返回的是NavigableString对象

item2_tag = item2[0].parent if item2 else None # 获取其父标签

```

IGNORE_WHEN_COPYING_START

content_copy

download

Use code with caution.

IGNORE_WHEN_COPYING_END


attrs 字典: 精确匹配多个属性。

python link = soup.find_all("a", attrs={"class": "nav next-link", "href": "/next"})


limit 参数: 限制返回结果的数量。

python first_two_paragraphs = soup.find_all('p', limit=2)


3. 遍历DOM树 (导航):


父节点: .parent, .parents (生成器,返回所有祖先)

python p_tag = soup.select_one('p.content') if p_tag: main_div_parent = p_tag.parent print(f"Parent of p.content: {main_div_parent.get('id')}") for ancestor in p_tag.parents: if ancestor.name == 'body': print("Found body ancestor") break


子节点: .contents (列表,包含所有子节点,包括文本节点), .children (生成器)

python main_div = soup.select_one('#main') if main_div: for child in main_div.children: # .children 更节省内存 if child.name: # 过滤掉NavigableString等非标签节点 print(f"Child tag: {child.name}")


后代节点: .descendants (生成器,包含所有后代,包括文本节点)


兄弟节点:

* .next_sibling, .previous_sibling (获取紧邻的下一个/上一个兄弟,可能是文本节点)

* .next_siblings, .previous_siblings (生成器)

* .find_next_sibling(name, attrs, ...): 查找符合条件的下一个兄弟标签。

* .find_previous_sibling(...)

* .find_all_next(...): 查找所有符合条件的后续兄弟标签。

* .find_all_previous(...)

python special_li = soup.select_one('li.special') if special_li: next_li = special_li.find_next_sibling('li') print(f"Next li after special: {next_li.get_text() if next_li else 'None'}")


4. 提取文本内容:


.string: 如果标签只包含一个文本节点或没有子标签,则返回该文本。否则返回 None。


.strings: 生成器,返回标签内所有直接和间接的文本节点(不包括空白)。


.stripped_strings: 生成器,同上,但会去除每个字符串两端的空白。


.get_text(separator="", strip=False): 获取标签内所有文本,拼接起来。

* separator: 指定字符串之间的分隔符。

* strip=True: 去除结果字符串两端的空白。

```python

main_div = soup.select_one('#main')

if main_div:

print(f"Main div text (raw): {main_div.get_text()}")

print(f"Main div text (stripped, space separated): {main_div.get_text(separator=' ', strip=True)}")


print("Stripped strings from main_div:")

for s in main_div.stripped_strings:

print(f"- '{s}'")

```


5. 修改DOM树:


修改标签名: tag.name = 'new_name'


修改属性: tag['attribute'] = 'new_value', del tag['attribute']


添加内容:

* tag.append(another_tag_or_string): 在末尾添加。

* tag.insert(index, another_tag_or_string): 在指定位置插入。


创建新标签: new_tag = soup.new_tag('b'), new_string = NavigableString(" (new)")


替换标签: tag.replace_with(another_tag_or_string)


移除标签:

* tag.decompose(): 将标签及其内容完全从树中移除并销毁。

* tag.extract(): 将标签及其内容从树中移除,并返回被移除的标签(可以后续使用)。


包裹/解包:

* tag.wrap(another_tag): 用另一个标签包裹当前标签。

* tag.unwrap(): 移除父标签,将当前标签的内容提升一级。


h1 = soup.select_one('h1.title')

if h1:

h1.string = "New Title" # 修改文本

h1['class'] = h1.get('class', []) + ['updated'] # 添加class

new_span = soup.new_tag('span', attrs={"style": "color:red;"})

new_span.string = "!"

h1.append(new_span) # 添加新标签

print(f"Modified H1: {h1}")


# 移除sidebar

sidebar = soup.select_one('.sidebar')

if sidebar:

sidebar.decompose()

# print(soup.prettify())

IGNORE_WHEN_COPYING_START

content_copy

download

Use code with caution.

Python

IGNORE_WHEN_COPYING_END


6. 处理不同的解析器:


Beautiful Soup支持多种解析器,它们在处理不规范HTML时的行为和速度可能不同:


'html.parser': Python内置解析器,无需额外安装,速度适中,容错性尚可。


'lxml': 非常快速,容错性好。需要安装 lxml 包。通常是首选。


'html5lib': 最容错的解析器,能像浏览器一样处理格式糟糕的HTML,但速度最慢。需要安装 html5lib 包。


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

# soup = BeautifulSoup(html_doc, 'lxml')

# soup = BeautifulSoup(html_doc, 'html5lib')

IGNORE_WHEN_COPYING_START

content_copy

download

Use code with caution.

Python

IGNORE_WHEN_COPYING_END


如果遇到解析问题,尝试更换解析器可能会有帮助。


7. 清理HTML (Pretty Print):


soup.prettify() 可以输出格式化(缩进)的HTML字符串,便于阅读和调试。


8. 检查属性是否存在:


tag.has_attr('attribute_name')


9. 复制标签:


如果你需要一个标签的副本进行修改而不影响原树,可以使用 copy.copy() (浅拷贝) 或 copy.deepcopy() (深拷贝)模块。


import copy

original_p = soup.select_one('p.content')

if original_p:

copied_p = copy.copy(original_p) # 浅拷贝,子节点还是指向原来的

deep_copied_p = copy.deepcopy(original_p) # 深拷贝,完全独立

deep_copied_p.string = "This is a deep copy"

# print(f"Original p: {original_p.get_text()}")

# print(f"Deep copied p: {deep_copied_p.get_text()}")

IGNORE_WHEN_COPYING_START

content_copy

download

Use code with caution.

Python

IGNORE_WHEN_COPYING_END


10. 搜索范围限定:


不要总是从 `soup` 对象开始搜索。如果你已经定位到了一个父元素,可以在该元素上调用 `find()`, `find_all()`, `select()` 等方法,以缩小搜索范围,提高效率和准确性。

```python

main_div = soup.select_one('#main')

if main_div:

# 只在 main_div 内部查找 p 标签

paragraphs_in_main = main_div.find_all('p')

```

IGNORE_WHEN_COPYING_START

content_copy

download

Use code with caution.

IGNORE_WHEN_COPYING_END


掌握这些技巧可以让你在使用Beautiful Soup时更加得心应手,能够处理更复杂的HTML结构和实现更精细的排版需求。最好的学习方式是结合官方文档多加练习。

点击这里复制本文地址 以上内容由朽木教程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

朽木教程网 © All Rights Reserved.  蜀ICP备2024111239号-8