python中BeautifulSoup库使用小结

发布时间 2023-11-11 23:51:25作者: 香吧香

转载请注明出处:

  BeautifulSoup是一个用于解析HTML和XML文档的Python库,它提供了一些简单但强大的API,让你可以从文档中提取数据。以下是一些BeautifulSoup的主要特性和功能:

  • 解析HTML和XML文档:BeautifulSoup可以解析HTML和XML文档,并创建一个BeautifulSoup对象,这个对象表示整个文档。可以使用这个对象来搜索和修改文档的元素。
  • 导航文档树:BeautifulSoup提供了一些方法,让你可以在文档树中导航。例如,可以使用find方法来搜索文档树中的元素,使用find_all方法来搜索所有匹配的元素,使用parentchildrendescendants等属性来访问元素的父元素,子元素和后代元素。
  • 搜索文档树:BeautifulSoup提供了一些方法,可以搜索文档树中的元素。例如,可以使用find方法来搜索文档树中的第一个匹配的元素,使用find_all方法来搜索所有匹配的元素,使用select方法来使用CSS选择器来搜索元素。
  • 修改文档树:BeautifulSoup提供了一些方法,可以修改文档树中的元素。例如,可以使用appendprependinsert_beforeinsert_after方法来添加新的元素,使用replace_with方法来替换元素,使用extract方法来移除元素。

  使用BeautifulSoup的示例:

from bs4 import BeautifulSoup

# 解析HTML文档
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

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

<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc, 'html.parser')

# 导航文档树
p = soup.find('p', class_='title')
print(p.name)  # 输出: p
print(p.string)  # 输出: The Dormouse's story

# 搜索文档树
links = soup.find_all('a')
for link in links:
    print(link.get('href'))  # 输出: http://example.com/elsie, http://example.com/lacie, http://example.com/tillie

# 修改文档树
p.string.replace_with('A new title')
print(p.string)  # 输出: A new title

  搜索相邻的元素标签值:

def job():
    
    soup = BeautifulSoup(html_doc, 'html.parser')
    target_a = soup.find('a', string='Elsie')
    print('target_a', target_a.text)
    if target_a is not None:
        target_a_next = target_a.find_next('a')
        print(target_a_next.text)
    else:
        print("No matching element found.")
 
job()