使用 Beautiful Soup 从嵌套标签中提取文本

使用 Beautiful Soup 从嵌套标签中提取文本

本文档旨在解决在使用 Beautiful Soup 解析 HTML 时,如何从嵌套标签中准确提取文本的问题。我们将通过实例演示如何使用 find_next(text=True) 方法以及 .get_text(strip=True) 方法来获取所需数据,并提供完整的代码示例和注意事项,帮助开发者更好地理解和应用 Beautiful Soup。

在使用 Beautiful Soup 解析 HTML 时,经常会遇到需要从嵌套标签中提取文本的情况。直接使用 .text 属性可能会遇到 AttributeError: ‘NoneType’ object has no attribute ‘text’ 错误,这通常是因为 Beautiful Soup 无法直接找到包含文本的标签。本文将介绍如何正确地从嵌套标签中提取文本,并提供示例代码。

使用 find_next(text=True) 方法

当目标文本位于一个标签内部的文本节点时,可以使用 find_next(text=True) 方法来定位到该文本节点,然后提取文本。

以下是一个示例 HTML 结构:

<div class="preview-content">     <a class="preview__link" href="/properties/1042-us-highway-1-hancock-me-04634/1330428">             <span class="preview__price">             $89,900         </span>         <span class="preview__size">             1 ac         </span>         <div class="preview__subtitle">             <h2 class="-g-truncated preview__subterritory">                 Hancock County             </h2>             <span class="preview__extended">                 -- sq ft             </span>         </div>     </a> </div>

以下是使用 find_next(text=True) 方法提取价格、大小和县域的代码示例:

from bs4 import BeautifulSoup  html = ''' <div class="preview-content">     <a class="preview__link" href="/properties/1042-us-highway-1-hancock-me-04634/1330428">             <span class="preview__price">             $89,900         </span>         <span class="preview__size">             1 ac         </span>         <div class="preview__subtitle">             <h2 class="-g-truncated preview__subterritory">                 Hancock County             </h2>             <span class="preview__extended">                 -- sq ft             </span>         </div>     </a> </div> '''  soup = BeautifulSoup(html, 'html.parser')  preview_content = soup.find('div', class_='preview-content')  if preview_content:     plot_price = preview_content.find('span', {"class": 'preview__price'}).find_next(text=True).strip()     plot_size = preview_content.find('span', {"class": 'preview__size'}).find_next(text=True).strip()     plot_county = preview_content.find('h2', class_='-g-truncated preview__subterritory').find_next(text=True).strip()      print(plot_price)     print(plot_size)     print(plot_county) else:     print("未找到 'preview-content' 类别的 div 元素")

代码解释:

  1. 首先,使用 BeautifulSoup 解析 HTML 字符串。
  2. 然后,使用 find() 方法找到 class 为 preview-content 的 div 元素。
  3. 对于每个需要提取的文本,先找到包含该文本的标签(例如,span 或 h2)。
  4. 使用 find_next(text=True) 方法找到标签内的文本节点。
  5. 使用 .strip() 方法去除文本节点前后的空格。

使用 .get_text(strip=True) 方法

.get_text(strip=True) 方法可以提取标签内的所有文本内容,并去除首尾空格。这个方法在处理包含多个子标签的复杂结构时非常有用。

使用 Beautiful Soup 从嵌套标签中提取文本

天工AI

昆仑万维推出的国内首款融入大语言模型的ai对话问答、AI搜索引擎,知识从这里开始。

使用 Beautiful Soup 从嵌套标签中提取文本247

查看详情 使用 Beautiful Soup 从嵌套标签中提取文本

以下是使用 .get_text(strip=True) 方法的示例:

from bs4 import BeautifulSoup  html = ''' <div class="preview-content">     <a class="preview__link" href="/properties/1042-us-highway-1-hancock-me-04634/1330428">             <span class="preview__price">             $89,900         </span>         <span class="preview__size">             1 ac         </span>         <div class="preview__subtitle">             <h2 class="-g-truncated preview__subterritory">                 Hancock County             </h2>             <span class="preview__extended">                 -- sq ft             </span>         </div>     </a> </div> '''  soup = BeautifulSoup(html, 'html.parser')  preview_content = soup.find('div', class_='preview-content')  if preview_content:     plot_price = preview_content.find('span', {"class": 'preview__price'}).get_text(strip=True)     plot_size = preview_content.find('span', {"class": 'preview__size'}).get_text(strip=True)     plot_county = preview_content.find('h2', class_='-g-truncated preview__subterritory').get_text(strip=True)      print(plot_price)     print(plot_size)     print(plot_county) else:     print("未找到 'preview-content' 类别的 div 元素")

代码解释:

此示例与前一个示例类似,但使用 .get_text(strip=True) 方法代替了 find_next(text=True) 方法。.get_text(strip=True) 方法直接提取标签内的文本内容,并去除首尾空格。

完整示例:从网页抓取数据

以下是一个从实际网页抓取数据的完整示例:

import requests from bs4 import BeautifulSoup  url = 'https://www.landsearch.com/industrial/united-states/p1' res = requests.get(url)  soup = BeautifulSoup(res.content, 'lxml')  landplots = soup.find_all('div', class_='preview-content')  for l in landplots:     try:         plot_price = l.find('span', {"class": 'preview__price'}).get_text(strip=True)         plot_size = l.find('span', {"class": 'preview__size'}).get_text(strip=True)         plot_county = l.find('h2', class_='-g-truncated preview__subterritory').get_text(strip=True)          print(plot_price)         print(plot_size)         print(plot_county)     except AttributeError:         print("部分信息缺失")

代码解释:

  1. 首先,使用 requests 库获取网页内容。
  2. 然后,使用 BeautifulSoup 解析 HTML 内容。
  3. 使用 find_all() 方法找到所有 class 为 preview-content 的 div 元素。
  4. 对于每个 div 元素,提取价格、大小和县域信息。
  5. 使用 try…except 块处理可能出现的 AttributeError 异常,例如当某个地块缺少某些信息时。

注意事项

  • 处理 NoneType 错误: 在提取文本之前,务必检查找到的标签是否为 None。如果标签不存在,尝试提取其文本属性会导致 AttributeError: ‘NoneType’ object has no attribute ‘text’ 错误。可以使用条件语句来避免此错误。
  • 网页结构变化: 网页结构可能会发生变化,因此需要定期检查代码是否仍然有效。如果网页结构发生变化,可能需要修改代码以适应新的结构。
  • 使用 strip() 方法: 提取文本后,建议使用 strip() 方法去除文本前后的空格,以确保数据的准确性。
  • 异常处理: 在实际应用中,建议使用 try…except 块来处理可能出现的异常,例如 AttributeError 和 TypeError。

总结

本文介绍了如何使用 Beautiful Soup 从嵌套标签中提取文本。通过使用 find_next(text=True) 方法和 .get_text(strip=True) 方法,可以准确地提取所需数据。同时,提供了完整的代码示例和注意事项,帮助开发者更好地理解和应用 Beautiful Soup。希望本文能够帮助读者解决在实际开发中遇到的问题。

html html beautifulsoup Object try 字符串 class Attribute

上一篇
下一篇