基于python做一个亚马逊和京东的比价系统,在系统界面上有待比价商品输入框,和比价按钮。可以选择在亚马逊和京东两个网站上检索商品。在flask web程序中控制比价流程,并返回比价结果。比价结果网页中展示出来,请将代码写出来

时间: 2024-04-21 17:27:57 浏览: 12
好的,下面是一个简单的实现代码,供您参考: ```python # coding:utf-8 import requests from bs4 import BeautifulSoup from flask import Flask, render_template, request import sqlite3 app = Flask(__name__) # 创建数据库 conn = sqlite3.connect('product.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS product (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, price FLOAT, link TEXT)''') conn.commit() # 爬取亚马逊商品信息 def crawl_amazon_product(name): url = 'https://www.amazon.com/s?k=' + name headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} r = requests.get(url, headers=headers) soup = BeautifulSoup(r.text, 'html.parser') products = soup.find_all('div', {'class': 's-result-item'}) for product in products: try: name = product.find('h2', {'class': 'a-size-mini'}).text.strip() price = float(product.find('span', {'class': 'a-price-whole'}).text.strip().replace(',', '')) link = 'https://www.amazon.com' + product.find('a', {'class': 'a-link-normal'})['href'] c.execute("INSERT INTO product (name, price, link) VALUES (?, ?, ?)", (name, price, link)) conn.commit() except: continue # 爬取京东商品信息 def crawl_jd_product(name): url = 'https://search.jd.com/Search?keyword=' + name headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} r = requests.get(url, headers=headers) soup = BeautifulSoup(r.text, 'html.parser') products = soup.find_all('div', {'class': 'gl-i-wrap'}) for product in products: try: name = product.find('div', {'class': 'p-name'}).text.strip() price = float(product.find('div', {'class': 'p-price'}).strong.i.text) link = 'https:' + product.find('div', {'class': 'p-name'}).a['href'] c.execute("INSERT INTO product (name, price, link) VALUES (?, ?, ?)", (name, price, link)) conn.commit() except: continue # 比价函数 def compare(name, site): # 先清空数据库 c.execute("DELETE FROM product") conn.commit() # 根据选择的网站爬取商品信息 if site == 'amazon': crawl_amazon_product(name) elif site == 'jd': crawl_jd_product(name) else: return [] # 从数据库中获取比价结果 c.execute("SELECT name, price, link FROM product ORDER BY price") result = c.fetchall() return result # 网页界面 @app.route('/') def index(): return render_template('index.html') # 比价操作 @app.route('/compare', methods=['POST']) def compare_products(): name = request.form['name'] site = request.form['site'] result = compare(name, site) return render_template('result.html', result=result) if __name__ == '__main__': app.run(debug=True) ``` 其中,`crawl_amazon_product()` 和 `crawl_jd_product()` 函数分别用于爬取亚马逊和京东的商品信息,并将爬取到的商品信息存储到数据库中。`compare()` 函数则用于比价操作,根据选择的网站爬取商品信息,然后从数据库中获取比价结果。 在网页界面中,我们提供了一个待比价商品输入框和一个下拉菜单,用户可以在输入框中输入待比价的商品名称,选择需要比价的网站(亚马逊或者京东),点击比价按钮后,程序会从数据库中获取对应的商品信息,并进行比价操作,最终返回比价结果。 具体的网页界面和展示结果的代码可以参照以下示例: ```html <!-- index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>比价系统</title> </head> <body> <h1>比价系统</h1> <form method="POST" action="/compare"> <label for="name">待比价商品:</label> <input type="text" name="name" id="name"> <br> <label for="site">选择网站:</label> <select name="site" id="site"> <option value="amazon">亚马逊</option> <option value="jd">京东</option> </select> <br> <button type="submit">比价</button> </form> </body> </html> ``` ```html <!-- result.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>比价结果</title> </head> <body> <h1>比价结果</h1> <table> <thead> <tr> <th>商品名称</th> <th>价格</th> <th>链接</th> </tr> </thead> <tbody> {% for item in result %} <tr> <td>{{ item[0] }}</td> <td>{{ item[1] }}</td> <td><a href="{{ item[2] }}" target="_blank">{{ item[2] }}</a></td> </tr> {% endfor %} </tbody> </table> </body> </html> ``` 以上代码仅供参考,具体的实现细节可能会有所不同,需要根据实际情况进行调整。

最新推荐

recommend-type

Python限制内存和CPU使用量的方法(Unix系统适用)

主要介绍了Python限制内存和CPU的使用量的方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
recommend-type

在python tkinter界面中添加按钮的实例

今天小编就为大家分享一篇在python tkinter界面中添加按钮的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

python实现超市商品销售管理系统

主要为大家详细介绍了python实现超市商品销售管理系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

python实现程序重启和系统重启方式

主要介绍了python实现程序重启和系统重启方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

不到40行代码用Python实现一个简单的推荐系统

主要给大家介绍了如何利用不到40行python代码实现一个简单的推荐系统,文中通过示例代码介绍的非常详细,对大家学习或者使用Python具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。