首页 > 解决方案 > 亚马逊价格跟踪器和推送通知

问题描述

作为我的第二个 python 项目,我正在尝试使用 3 行用于桌面推送通知的额外代码https://www.youtube .com/watch?v=KshTf2A5aUk ) 而不是电子邮件。当我运行代码时,我没有收到错误消息,但也没有收到推送通知。你有什么想法吗?

我的代码如下:

import requests
from bs4 import BeautifulSoup
import win10toast

URL = 'https://www.amazon.de/WOTR-Elektro-Skateboard-Off-Road-vierr%C3%A4drige-Elektroroller-Fernbedienung/dp/B07ZX6TV79/ref=sr_1_25?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&dchild=1&keywords=e+skateboard&qid=1597239289&sr=8-25'

headers = {"User Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0'}

def check_price():
    page = requests.get(URL, headers=headers)

    soup = BeautifulSoup(page.content, 'html.parser')

    title = soup.find(id="productTitle").get_text()

    price = soup.find(id="priceblock_ourprice").get_text()
    converted_price = float(price[0:4])

    if(converted_price > 700):
        send_alert()

    print(converted_price)
    print(title.strip())

def send_alert():
        toaster = win10toast.ToastNotifier().show_toast("Python", 'Cheaper', duration=5)

标签: pythonwebscreen-scraping

解决方案


你需要调用check_price()函数来运行你的代码,而且converted_price = float(price[0:4])这段代码会给你一个错误,你应该这样做,split()所以它会像100-999price[0:3]一样精确,但如果它是999+,它将转换错误的价格。

以下是修改后的代码:

import requests
from bs4 import BeautifulSoup
import win10toast
import time

URL = 'https://www.amazon.de/WOTR-Elektro-Skateboard-Off-Road-vierr%C3%A4drige-Elektroroller-Fernbedienung/dp/B07ZX6TV79/ref=sr_1_25?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&dchild=1&keywords=e+skateboard&qid=1597239289&sr=8-25'

headers = {"User Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0'}

def check_price():
    page = requests.get(URL, headers=headers)

    soup = BeautifulSoup(page.content, 'html.parser')

    title = soup.find(id="productTitle").get_text()

    price = soup.find(id="priceblock_ourprice").get_text()
    converted_price = float(price.split(",")[0])
    print(converted_price)

    if(converted_price > 700):
        send_alert()

    print(converted_price)
    print(title.strip())

def send_alert():
        toaster = win10toast.ToastNotifier().show_toast("Python", 'Cheaper', duration=5)

while True:
    check_price()
    time.sleep(5) #sleep 5 seconds before requesting the price again

推荐阅读