python输入产品名称,就可以下载某购物网产品信息,例如:标题、价格与链结网址,然后将其下载至本地端。 可以让使用者决定价格优先,还是评价优先呈现结果。 爬虫结果输出类型为json(10%)或者储存在MongoDB,代码
时间: 2024-06-09 14:12:02 浏览: 11
好的,对于您的问题,我建议您使用 Python 的 requests、BeautifulSoup 和 pymongo 库来实现。以下是一个简单的代码示例,可以根据产品名称从某购物网站爬取产品信息,并将其储存在 MongoDB 中:
```python
import requests
from bs4 import BeautifulSoup
import pymongo
# 连接 MongoDB 数据库
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client['product_info']
collection = db['products']
# 输入产品名称和排序方式
product_name = input('请输入产品名称:')
sort_by = input('按价格排序请输入 1,按评价排序请输入 2:')
# 构造查询 URL
if sort_by == '1':
url = f'https://www.xxx.com/search?q={product_name}&sort=price_asc'
else:
url = f'https://www.xxx.com/search?q={product_name}&sort=sales_desc'
# 发送 GET 请求
response = requests.get(url)
# 解析 HTML 页面
soup = BeautifulSoup(response.text, 'html.parser')
products = soup.find_all('div', {'class': 'product-item'})
# 遍历每个产品并保存到 MongoDB 中
for product in products:
title = product.find('a', {'class': 'product-title'}).text.strip()
price = product.find('span', {'class': 'product-price'}).text.strip()
link = product.find('a', {'class': 'product-title'})['href']
collection.insert_one({'title': title, 'price': price, 'link': link})
# 查询结果
for product in collection.find():
print(product)
```
您可以根据自己的需要定制代码。请注意,在使用爬虫时,请遵守网站的使用条款,并确保您的爬虫行为不会对网站造成过大的负担。