[英]How can i write into csv file 2 different comments based on returned result using Python
我正在尝试运行亚马逊价格检查器,我想要实现的是,如果价格 < target_price 发送电子邮件(稍后我将添加此部分)并写入 csv 文件时间戳和日期、价格和评论价格已经下降和 email如果 price > target_price 不发送 email 则发送其他内容,只需写入 csv 文件时间戳和日期,评论价格太高 email 将不会发送。
这是我的代码
import csv
import requests
from bs4 import BeautifulSoup
import datetime
import os
import time
# Requirement
# 1- Check Price
url = 'https://www.amazon.co.uk/Amazon-Fire-TV-Stick-4K-Ultra-Hd-With-Alexa-Voice-Remote-Streaming-Media-Player/dp/B079QB9BD7/ref=sr_1_2_mod_primary_new?dchild=1&keywords=amazon+fire+stick&qid=1608568582&sbo=RZvfv%2F%2FHxDF%2BO5021pAnSA%3D%3D&sr=8-2'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}
def check_stick_price():
# this makes the request
page = requests.get(url, headers=headers)
# this extracts from page and parses into html
bs = BeautifulSoup(page.content, 'html.parser')
# this gives us the product name by using 'productTitle' id - by adding .get_text() allows you to get display the text
product_title = bs.find(id="productTitle").get_text()
# this gets the price by using 'priceblock_dealprice' id
price = bs.find(id="priceblock_ourprice").get_text()
print(product_title.strip())
return price
# Compare Price
price = check_stick_price()
target_price = str("£30")
# Create a file
file_exists = True
if not os.path.exists("../../MyProjects/Aamazon/price.csv"):
file_exists = False
with open("../../MyProjects/Aamazon/price.csv", "a") as file:
writer = csv.writer(file, lineterminator='\n')
fields = ["Timestamp", "Price", "Comments"]
if not file_exists:
writer.writerow(fields)
if target_price > price:
comment_email_Not_Sent = "too high email will not be sent"
string = "Price is {}" # place holder for above
output = string.format(comment_email_Not_Sent)
else:
comment_email_Sent = "fallen and email was sent"
string2 = " Price has {}" # place holder for above
output2 = string2.format(comment_email_Sent)
timestamp = f"{datetime.datetime.date(datetime.datetime.now())} | {datetime.datetime.time(datetime.datetime.now())}"
writer.writerow([timestamp, price, output, output2])
print("wrote data to file")
如果我删除评论部分中的 if 条件,它会将两个评论都写入文件,而不管结果如何
任何帮助表示赞赏
你不能就这样吗
if target_price > price:
output = "Price is too high email will not be sent"
else:
output = "Price has fallen and email was sent"
接着
writer.writerow([timestamp, price, output])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.