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

如何用BeautifulSoup4抓取无class、id属性的网页内容并导出为CSV

基于BeautifulSoup4的目标内容抓取实现方案

实现思路

目标页面的机构信息有固定的结构规律:每个独立机构的信息由「包含机构名称a标签的h2标签」+「紧邻h2的p标签(存放所有字段信息)」成对组成,我们可以通过该结构规律定位目标内容,无需依赖class或id属性。

依赖安装

先安装需要的第三方库:

pip install requests beautifulsoup4

完整实现代码

import csv
import requests
from bs4 import BeautifulSoup

# 请求头配置,避免反爬拦截
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
}
# 目标页面URL
TARGET_URL = "https://www.re-thinkingthefuture.com/top-architects/top-architecture-firms-in-india-part-1/"
# 英文标识和中文表头的映射
FIELD_MAP = {
    "Scope of services": "服务范围",
    "Types of Built Projects": "建成项目类型",
    "Locations of Built Projects": "建成项目位置",
    "Style of work": "工作风格",
    "Website": "网站"
}
# CSV表头
CSV_HEADERS = ["机构名称"] + list(FIELD_MAP.values())

def main():
    # 发起请求获取页面内容
    resp = requests.get(TARGET_URL, headers=HEADERS)
    resp.encoding = "utf-8"
    soup = BeautifulSoup(resp.text, "html.parser")
    
    result_list = []
    # 遍历所有包含机构名称的h2标签
    for h2 in soup.find_all("h2"):
        a_tag = h2.find("a")
        if not a_tag:
            continue
        # 提取机构名称
        org_name = a_tag.get_text(strip=True)
        # 找到紧邻h2的信息p标签
        info_p = h2.find_next_sibling("p")
        if not info_p:
            continue
        
        # 替换br标签为换行符,方便按字段拆分
        for br in info_p.find_all("br"):
            br.replace_with("\n")
        
        item = {"机构名称": org_name}
        # 遍历p标签下的所有b标签(每个b标签对应一个字段标识)
        for b_tag in info_p.find_all("b"):
            field_key = b_tag.get_text(strip=True).rstrip(":")
            if field_key not in FIELD_MAP:
                continue
            # 提取b标签后面的所有文本内容,去除多余空格和冒号
            field_value = b_tag.next_sibling
            if field_value:
                field_value = field_value.strip().lstrip(":").strip()
            # 特殊处理网站字段,提取a标签文本
            if field_key == "Website":
                a_tag = b_tag.find_next_sibling("span").find("a")
                if a_tag:
                    field_value = a_tag.get_text(strip=True)
            item[FIELD_MAP[field_key]] = field_value if field_value else ""
        
        result_list.append(item)
    
    # 写入CSV文件
    with open("印度建筑公司信息.csv", "w", encoding="utf-8-sig", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=CSV_HEADERS)
        writer.writeheader()
        writer.writerows(result_list)

if __name__ == "__main__":
    main()

注意事项

  • 代码默认提取网站字段的文本内容,若需要提取完整网址,可将网站字段的取值逻辑改为a_tag["href"]
  • 若页面有格式异常的内容,可在遍历逻辑中增加try-except异常捕获,避免单条数据异常导致整个程序中断
  • 输出的CSV文件使用utf-8-sig编码,可直接用Excel打开不会出现乱码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 06:30:05