我的知识记录

Python BeautifulSoup解析网页提取文字:标签选择与清洗

讲解用BeautifulSoup解析HTML,通过find、select定位标签,提取正文文字并去掉多余空白,适合从抓取到的网页中抽取需要的文本内容。

场景痛点

requests拿到网页HTML后是一长串标签代码,混着导航、广告、脚本,直接看根本找不到正文。BeautifulSoup能把HTML解析成一棵标签树,像查字典一样按标签名、class、id找到目标元素,再把里面的文字干净地取出来。

用到的库

pip install requests beautifulsoup4 lxml

完整代码

# 导入库
import requests
from bs4 import BeautifulSoup

def extract_text(url):
# 先抓网页
headers = {
"User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 Chrome/124.0.0.0 Safari/537.36"),
}
resp = requests.get(url, headers=headers, timeout=10)
resp.encoding = resp.apparent_encoding

# 用lxml解析器把HTML变成BeautifulSoup对象
soup = BeautifulSoup(resp.text, "lxml")

# 去掉脚本和样式,这些不是正文
for tag in soup(["script", "style"]):
tag.decompose()

# 找所有段落标签,逐个提取文字
paragraphs = soup.find_all("p")
print(f"找到 {len(paragraphs)} 个段落")

texts = []
for p in paragraphs:
# .get_text() 取标签内所有文字(包括子标签里的)
text = p.get_text(strip=True)
if text:  # 去掉空行
texts.append(text)

# 找页面标题
title = soup.title.get_text(strip=True) if soup.title else "无标题"
print("页面标题:", title)

# 也支持CSS选择器
# soup.select("div.article h2")  # 找div.article下所有h2

return title, texts

def clean_whitespace(text):
"""把连续空白压成一个空格"""
return " ".join(text.split())

def main():
# 示例用一个简单的公开页面
url = "https://example.com"
title, texts = extract_text(url)

print("=" * 40)
print("正文前几段:")
for t in texts[:5]:
print("-", clean_whitespace(t)[:100])

if __name__ == "__main__":
main()

代码讲解

  • BeautifulSoup(html, "lxml") 把HTML字符串解析成对象,第二个参数 lxml 是解析器,速度快容错好,需要单独装lxml库。
  • soup.find_all("标签名") 找到所有该标签的元素,返回列表;soup.find("标签名") 只找第一个。
  • tag.get_text(strip=True) 把标签内部的所有文字拼接成字符串,strip=True 去掉首尾空白。
  • tag.decompose() 把没用的标签(script、style)从树上删掉,避免它们的内容混进正文。
  • soup.select("CSS选择器") 支持写CSS表达式,例如 div.content > p.title,复杂定位比find_all更直观。
  • 正文里经常有多余换行和空格,用 " ".join(text.split()) 一行代码压缩成干净文本。

运行结果

运行后会打印页面标题、找到的段落数量,以及前几段清洗后的文字。当前目录不需要额外输出文件,结果直接打印在控制台。

注意事项

  • 不同网站HTML结构差异很大,写选择器前先在浏览器F12里看清楚目标元素的标签和class。
  • 有些网页是JS动态渲染的,requests拿到的HTML里没有数据,这种情况要找接口或者用浏览器自动化。
  • lxmlhtml.parser 快,遇到畸形HTML容错也好,推荐装。
  • 提取文字后注意二次清洗:去掉广告水印、导航链接、版权声明。

Python BeautifulSoup解析网页提取文字:标签选择与清洗

标签:

更新时间:2026-09-14 20:50:59

上一篇:Python requests批量下载文件:多线程提速与失败重试

下一篇:Python BeautifulSoup提取表格数据:HTML表格转CSV示例