爬虫爬取京东手机数据,内容包括店铺名,价格,评论数,手机颜色,品牌。要求可以i自己输入爬取几页,并且爬取后将信息保存为csv
时间: 2024-03-28 07:39:54 浏览: 15
好的,对于这个问题,我们可以在上一个问题中的代码基础上,再加上将爬取的信息保存为 CSV 文件的功能。
具体实现如下:
```
import requests
from bs4 import BeautifulSoup
import csv
# 输入要爬取的页数
pages = int(input("请输入要爬取的页数:"))
# 创建一个新的 CSV 文件
with open("手机信息.csv", "w", newline="", encoding="utf-8-sig") as csvfile:
writer = csv.writer(csvfile)
# 添加表头
writer.writerow(["店铺名", "价格", "评论数", "手机颜色", "品牌"])
# 循环爬取每一页的数据
for page in range(1, pages+1):
url = f"https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&page={page}"
# 发送请求
response = requests.get(url)
# 解析网页内容
soup = BeautifulSoup(response.text, "html.parser")
# 获取所有商品列表
items = soup.find_all("div", class_="gl-i-wrap")
# 遍历商品列表,提取需要的数据
for item in items:
# 店铺名
shop = item.find("div", class_="p-shop").a.string.strip()
# 价格
price = item.find("div", class_="p-price").i.string.strip()
# 评论数
comment = item.find("div", class_="p-commit").a.string.strip()
# 手机颜色
color = item.find("div", class_="p-name").em.string.strip()
# 品牌
brand = item.find("div", class_="p-name").a.string.strip()
# 将爬取的信息保存到 CSV 文件中
writer.writerow([shop, price, comment, color, brand])
```
在这个示例中,我们使用了 csv 模块来创建一个新的 CSV 文件,并添加表头。然后在循环遍历商品列表的过程中,将需要的信息写入 CSV 文件中。
需要注意的是,这个示例中,我们使用了 `encoding="utf-8-sig"` 来指定编码格式,这是因为有些中文字符在默认编码格式下会出现乱码。如果需要在实际项目中使用,还需要考虑一些其他的问题,比如异常处理、文件路径等。