You need to enable JavaScript to run this app. 使用BeautifulSoup爬取网页提取目标字段存CSV并去除HTML标签
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup爬取网页提取目标字段存CSV并去除HTML标签

BeautifulSoup爬取AGTTA站点个人信息实现指南

爬取目标

  • 待爬取页面地址:https://www.agtta.co.in/individuals.php
  • 需提取的核心字段:个人姓名、手机号码、联系邮箱
  • 输出要求:所有采集到的结构化数据保存为CSV格式文件,表头固定为Name、Mobilenumber、Email

现有可运行基础代码

当前已完成带自定义User-Agent的请求模块,可正常绕过基础反爬、定位到页面目标内容区块,代码片段如下:

from bs4 import BeautifulSoup
import urllib.request
urls = ['https://www.agtta.co.in/individuals.php']
for url in urls:
    req = urllib.request.Request(
        url,
        headers={
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
        }
    )
    resp = urllib.request.urlopen(req)
    soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'), features='html.parser')
    scrape_data = soup.find('section', class_='b-branches')
    to_list = scrape_data.find_all_next(string=True)

开发中遇到的卡点

目前按如下遍历逻辑提取姓名字段时,输出结果会附带完整HTML标签:

for biz in results:
    # print(biz)
    title = biz.findAll('h3', {'class': 'b-branches__title ui-title-inner ui-title-inner_lg'})
    print(title)

实际返回内容类似:[<h3 class="b-branches__title ui-title-inner ui-title-inner_lg">SHRI RAMESHBHAI P. SAKARIYA</h3>],无法直接获取纯文本格式的字段值,需要完成标签剥离处理。

解决方案

  • 调用BeautifulSoup节点对象的.text属性,可直接剥离外层HTML标签,获取节点内部的纯文本内容
  • 按照页面DOM的层级结构,逐个定位姓名、手机号、邮箱对应的DOM节点,通过相同的.text方法提取纯文本值
  • 引入Python内置csv模块,将提取到的结构化字段按指定表头写入本地CSV文件

调整后的核心功能代码:

import csv
# 定位每个独立的人员信息卡片区块
biz_blocks = scrape_data.find_all('div', class_='b-branches__item')
# 初始化CSV写入对象,配置表头
with open('agtta_individuals.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerow(['Name', 'Mobilenumber', 'Email'])
    for biz in biz_blocks:
        # 提取纯文本姓名,替换原有带标签的返回结果
        name_node = biz.find('h3', {'class': 'b-branches__title ui-title-inner ui-title-inner_lg'})
        name = name_node.text.strip()
        # 定位手机号、邮箱对应链接节点,同样提取纯文本
        mobile_node = biz.find('a', {'href': lambda x: x and x.startswith('tel:')})
        mobile = mobile_node.text.strip()
        email_node = biz.find('a', {'href': lambda x: x and x.startswith('mailto:')})
        email = email_node.text.strip()
        # 写入当前行数据
        writer.writerow([name, mobile, email])

最终CSV输出参考

Name, Mobilenumber, Email
SHRI RAMESHBHAI P. SAKARIYA, 9876543210, sakariya@example.com

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 16:57:03