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

如何用Python的BeautifulSoup抓取同标签同类的网页元素?

爬虫问题解决方法

问题原因

你使用的find()方法仅会返回匹配到的第一个元素,而每个two_third last类的div内包含多组适应症(抑郁、疼痛)与对应价格的组合,因此只能获取到第一组数据,后续实例无法被提取。

修正方案

  1. 使用find_all()替代find(),获取所有适应症和对应价格的列表
  2. 遍历适应症与价格的配对列表,将每组数据与诊所的地址、电话、邮箱关联
  3. 提取元素的文本内容(通过.text.strip()),确保DataFrame存储的是可读字符串而非Tag对象

修正后的代码

import requests
from bs4 import BeautifulSoup
import pandas as pd

website = 'https://ketamineclinicsdirectory.com/'
result = requests.get(website)
content = result.text

soup = BeautifulSoup(content, 'lxml')

clinics = soup.find_all('div', class_='two_third last')

all_data = []

for item in clinics:
    # 获取所有适应症和对应价格的列表
    use_cases = item.find_all('span', class_='declaration')
    price_per_infusions = item.find_all('span', class_='price')
    # 获取诊所的地址、电话、邮箱
    address = item.find('span', class_='address').text.strip() if item.find('span', class_='address') else None
    phone = item.find('span', class_='phone').text.strip() if item.find('span', class_='phone') else None
    email = item.find('span', class_='email').text.strip() if item.find('span', class_='email') else None
    
    # 遍历配对适应症和价格
    for use_case, price in zip(use_cases, price_per_infusions):
        all_data.append({
            'use_case': use_case.text.strip(),
            'price_per_infusion': price.text.strip(),
            'address': address,
            'phone': phone,
            'email': email
        })

df = pd.DataFrame(all_data)
print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:02:09