当前位置:首页>python>python爬虫篇之bs4实战2:爬取北京新发地

python爬虫篇之bs4实战2:爬取北京新发地

  • 2026-09-02 19:05:44
python爬虫篇之bs4实战2:爬取北京新发地

4.11

bs4实战2:爬取北京新发地

今天,让我们找个网站进行bs4实战看看。

1

爬取北京新发地

import requestsimport csvimport time# 请求数据url = "http://www.xinfadi.com.cn/getCat.html"response = requests.post(url, data={"limit": 100})# 创建CSV文件filename = f"菜价数据_{time.strftime('%Y%m%d')}.csv"with open(filename, 'w', newline='', encoding='utf-8-sig') as csvfile:    writer = csv.writer(csvfile)    writer.writerow(['商品名称', '最低价', '平均价', '最高价', '单位'])    # 处理数据    if response.status_code == 200:        data = response.json()        for product in data.get('list', []):            writer.writerow([                product.get('prodName', ''),                product.get('lowPrice', ''),                product.get('avgPrice', ''),                product.get('highPrice', ''),                product.get('unitInfo', '')            ])        print(f"成功保存 {len(data.get('list', []))} 条数据到 {filename}")    else:        print(f"请求失败,状态码: {response.status_code}")        writer.writerow(['错误信息', f'请求失败,状态码: {response.status_code}'])

  python爬虫须知

🔸 守规矩:爬前先看 robots.txt,尊重网站规则。

🔸 有礼貌:设置访问间隔(如 time.sleep),别把服务器挤爆。

🔸 装得像:带上合理 User-Agent和请求头,模拟真人浏览器。

🔸 不越界:绝不爬取个人隐私、机密或明确禁止的数据。

🔸 存得好:妥善处理数据,注明来源,注意脱敏。

最新文章

随机文章