You need to enable JavaScript to run this app. 使用Beautiful Soup爬取构建DataFrame时如何移除字段冗余文本
优惠活动
大模型
产品
解决方案
定价
更多

使用Beautiful Soup爬取构建DataFrame时如何移除字段冗余文本

问题根源

当前代码对简介模块直接调用.text属性,会把模块内包含的“Description”标题、正文内容全部拼接提取,因此最终结果会在开头附带不需要的固定标题文本。

实现方案

以下两种修改方式均可直接适配现有代码逻辑,改动量极小:

方案1:精准定位正文标签,从源头规避冗余

雅虎财经的页面结构中,“Description”是独立的标题元素,公司实际业务介绍正文放置在同一模块下的<p>标签内,直接提取该标签的文本即可完全消除冗余内容。
对应修改的代码片段:

# 定位整个简介模块
profile_section = soup.find('section', {'class':'quote-sub-section Mt(30px)'})
records.append({
    'symbol' : s,
    'Name': soup.h1.text.strip(),
    'Sector': soup.select_one('span:contains("Sector(s)") + span').text.strip(),
    'Industry': soup.select_one('span:contains("Industry") + span').text.strip(),
    # 直接提取模块内正文p标签的文本,无冗余标题
    'Description': profile_section.find('p').text.strip()
})

方案2:提取后清理固定前缀,兼容页面结构小幅变动

如果担心后续页面结构调整导致p标签定位失效,可以保留全量模块文本提取逻辑,使用Python内置的removeprefix方法仅删除字符串开头匹配的“Description”内容。该方法不会误删正文部分出现的相同关键词,比全局字符串替换的安全性更高。
对应修改的代码片段:

# 获取模块全量文本
full_section_text = soup.find('section', {'class':'quote-sub-section Mt(30px)'}).text
# 仅移除开头匹配的固定冗余文本
'Description': full_section_text.removeprefix('Description').strip()

注:removeprefix为Python 3.9及以上版本内置方法,如果使用更低版本的Python,可以用切片实现相同效果:full_section_text[len('Description'):].strip()

完整可运行的修改后代码

补充常规请求头避免被网站反爬拦截,可直接运行得到预期效果:

import requests
from bs4 import BeautifulSoup as bs
import pandas as pd


records = []
tickers = ['FSLR']

url = 'https://finance.yahoo.com/quote/{}/profile?p={}'
# 模拟浏览器请求头,避免被反爬拦截
request_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}

for s in tickers:
    response = requests.get(url.format(s,s), headers=request_headers)
    soup = BeautifulSoup(response.content, 'html.parser')
    profile_section = soup.find('section', {'class':'quote-sub-section Mt(30px)'})

    records.append({
        'symbol' : s,
        'Name': soup.h1.text.strip(),
        'Sector': soup.select_one('span:contains("Sector(s)") + span').text.strip(),
        'Industry': soup.select_one('span:contains("Industry") + span').text.strip(),
        'Description': profile_section.find('p').text.strip()
    })

df = pd.DataFrame(records)
df.head()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 12:45:04