You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python爬虫使用BeautifulSoup如何仅提取<a>标签的文本内容

Python 提取指定a标签文本的实现方案
  • 第一步:安装依赖库
    如果还没安装requests和beautifulsoup4,先执行如下安装命令:
pip install requests beautifulsoup4
  • 第二步:完整抓取提取代码
import requests
from bs4 import BeautifulSoup

# 替换为实际要抓取的页面URL
target_url = "替换为你的目标页面地址"
# 发送请求获取页面内容
resp = requests.get(target_url)
# 手动指定编码适配法语站点,避免乱码
resp.encoding = "utf-8"

# 解析HTML
soup = BeautifulSoup(resp.text, "html.parser")

# 定位目标a标签,可根据实际情况选择匹配规则
# 规则1:按title属性匹配
target_tag = soup.find("a", title="Synonyme du mot À côté")
# 规则2:按href属性匹配(可选)
# target_tag = soup.find("a", href="https://www.synonymeur.com/synonyme/a-cote/")

if target_tag:
    # 直接取text属性即可获得标签内的纯文本,strip()用于去除首尾空白字符
    result = target_tag.text.strip()
    print(result) # 输出结果为:À côté
else:
    print("未定位到目标标签")

如果你仅需要测试单独HTML片段的提取效果,可以使用如下简化代码:

from bs4 import BeautifulSoup

# 填入你的HTML片段
html_sample = '<a href="https://www.synonymeur.com/synonyme/a-cote/" title="Synonyme du mot À côté">À côté</a>'
soup = BeautifulSoup(html_sample, "html.parser")
print(soup.find("a").text.strip()) # 输出:À côté

内容的提问来源于stack exchange,提问作者ilyass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:45:11