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

Python爬取非处方药品数据终端可打印但75条记录无法存入CSV文件

问题根源

  • 存储爬取数据的列表suit被定义在了分页遍历的循环内部,每处理完一页跳转下一页时,都会清空之前所有页的存储数据,最终列表仅保留最后一页的内容,导致导出的CSV只有少量记录
  • 代码中使用Python内置关键字property作为循环变量名,存在潜在的语法冲突风险

修复后代码

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

# 把存储列表移到分页循环外部
suit = []
for page_number in range(1, 6):
    url = f'https://sehat.com.pk/categories/Over-The-Counter-Drugs/Diarrhea-and-Vomiting-/?sort=featured&page='+str(page_number)
    r = requests.get(url)
    # 保留低频率延时,避免被站点反爬拦截
    time.sleep(2)
    soup = BeautifulSoup(r.content, 'html.parser')
    content = soup.find_all('div', class_ = 'col-md-12 pr-0 pl-0')
    # 更换循环变量名为非关键字命名
    for product_item in content:
        names = product_item.find('div',class_='col-md-12 d-table-cell align-middle')
        name= names.find('img', class_ = 'img-fluid')['alt']
        links=product_item.find('a')['href']
        try:
            price= product_item.find('div', class_ = 'ProductPriceRating d-table-cell text-center pl-1 pr-1 align-middle').text.strip()
        except AttributeError:
            price=''
        try:
            product_brand =product_item.find('div',class_ ='ProductBoxProductBrand-div d-table-row text-center pl-1 pr-1 align-middle').text.strip()
        except AttributeError:
            product_brand=''
        print(name,product_brand,links,price)

        fabric = {
            'productname':name,
            'product_Brand':product_brand,
            'Product_price': price,
            'links': links,
        }    
        suit.append(fabric)
print ("正在导入数据到CSV文件...!!")
df = pd.DataFrame(suit)
print("保存成功....")
# 新增编码参数避免Windows系统下打开CSV乱码
df.to_csv('Diarrhea_and_Vomiting_pagination.csv', index=False, encoding='utf-8-sig')

补充说明

修改后所有分页的75条数据都会被存入列表,最终完整导出到CSV文件中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:39:03