基于python做一个亚马逊和京东的比价系统,在系统界面上有待比价商品输入框,和比价按钮。可以选择在亚马逊和京东两个网站上检索商品。在flask web程序中控制比价流程,并返回比价结果。比价结果网页中展示出来,请将代码写出来
时间: 2024-04-21 13:27:57 浏览: 150
好的,下面是一个简单的实现代码,供您参考:
```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>
```
以上代码仅供参考,具体的实现细节可能会有所不同,需要根据实际情况进行调整。
阅读全文