สร้างบอตติดตามราคา
พัฒนาบอตที่ตรวจสอบราคาสินค้าบนเว็บไซต์อีคอมเมิร์ซและส่งการแจ้งเตือนเมื่อราคาลดลง
สร้างบอตติดตามราคา เป็นบทเรียน Web Scraping & Bots ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Web Scraping & Bots และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Web Scraping & Bots มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What's a Price Tracker Bot?
Have you ever wanted to know when a product's price drops? A price tracker bot does exactly that!
It's an automated program that regularly checks the price of items on e-commerce websites.
When it detects a price change, especially a drop, it can notify you.
Bot's Core Tasks
Building a price tracker involves several key steps:
- Fetch: Get the product page content.
- Parse: Extract the price and product details.
- Store: Keep track of the last known price.
- Compare: Check if the current price is lower.
- Notify: Send an alert if a drop is found.
Spotting Product Details
Before we write code, we need to know where the information is on the page.
Using browser developer tools, you'd identify the HTML elements that contain the product's:
- Name
- Current Price
- Product URL
These are crucial for your bot to find the right data.
Getting the Web Page
The first step is to download the web page content. We'll use the requests library for this.
It sends an HTTP GET request to the product URL and retrieves the HTML.
Try running this simple example:
import requests
def fetch_page(url):
try:
response = requests.get(url)
response.raise_for_status() # Check for HTTP errors
return response.text
except requests.exceptions.RequestException as e:
print(f"Error fetching page: {e}")
return None
if __name__ == "__main__":
# Example URL (replace with a real product page for testing)
example_url = "https://example.com/product"
print(f"Fetching content from: {example_url}")
# In a real bot, you'd parse this content
# page_content = fetch_page(example_url)
# if page_content:
# print("Page content fetched successfully (first 200 chars):")
# print(page_content[:200])
# else:
# print("Failed to fetch page content.")
print("Page content fetching logic demonstrated.")Parsing the Price
Once you have the HTML, you'll use a library like BeautifulSoup to parse it and find the price.
Prices often come with currency symbols or extra text, so we'll need to clean the extracted string to get a numeric value.
Here's a snippet to illustrate:
from bs4 import BeautifulSoup
html_doc = """
<html><body>
<span class="product-price">$199.99</span>
<div id="item-name">Cool Gadget</div>
</body></html>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
price_element = soup.find('span', class_='product-price')
if price_element:
price_string = price_element.get_text()
# Clean the string to get a float
cleaned_price = float(price_string.replace('$', '').strip())
print(f"Extracted Price: {cleaned_price}")
else:
print("Price element not found.")Remembering the Price
To track changes, your bot needs to remember the price it last saw. A simple way is to use a file to store this data.
For a basic bot, a JSON file or a simple dictionary in memory can work.
You'll store the product URL and its last known price.
import json
# Example of storing data
product_data = {
"https://example.com/product1": {
"name": "Cool Gadget",
"last_price": 199.99
},
"https://example.com/product2": {
"name": "Awesome Widget",
"last_price": 49.95
}
}
# In a real bot, you'd load/save this from a file
# with open('prices.json', 'w') as f:
# json.dump(product_data, f, indent=2)
print("Product data structure for storage:")
print(json.dumps(product_data, indent=2))Detecting Price Drops
This is the core logic! After fetching and parsing the new price, you compare it with the stored "last price".
If the new price is lower than the stored price, you've found a deal!
You should also update the stored price with the new one for future comparisons.
current_price = 189.99
stored_price = 199.99
product_name = "Cool Gadget"
if current_price < stored_price:
print(f"PRICE DROP ALERT! {product_name} is now ${current_price} (was ${stored_price})")
# Update stored_price = current_price in your data
elif current_price > stored_price:
print(f"Price increased for {product_name}. Current: ${current_price}, Was: ${stored_price}")
# Update stored_price = current_price
else:
print(f"Price for {product_name} remains ${current_price}")Notifying About Deals
Once a price drop is detected, your bot needs to tell you!
For a simple bot, printing a message to the console is enough. For real-world use, you might:
- Send an email
- Push a notification to your phone
- Send a message to a chat app (e.g., Discord, Telegram)
def send_notification(product_name, old_price, new_price):
message = (
f"🚨 Price Drop Alert! 🚨\n"
f"Product: {product_name}\n"
f"Old Price: ${old_price:.2f}\n"
f"New Price: ${new_price:.2f}\n"
f"Check it out now!"
)
print(message)
# In a real app, you'd integrate email/SMS here
if __name__ == "__main__":
send_notification("Awesome Headphones", 250.00, 225.00)Your First Price Tracker
Let's combine these pieces into a basic, runnable price tracker. This example simulates fetching and parsing.
Remember, for a real bot, you'd replace the `mock_fetch_and_parse` with actual requests and BeautifulSoup calls.
import json
import random
# Mock functions for demonstration
def mock_fetch_and_parse(product_url):
# Simulate different prices
if "gadget" in product_url:
return random.choice([199.99, 189.99, 205.00])
return random.choice([49.95, 45.00, 52.00])
def send_notification(product_name, old_price, new_price):
print(f"🚨 Price Drop! {product_name} is now ${new_price:.2f} (was ${old_price:.2f})")
# Main logic
def check_price(product_url, product_name, stored_prices):
current_price = mock_fetch_and_parse(product_url)
last_price = stored_prices.get(product_url)
if last_price is None:
print(f"First check for {product_name}: ${current_price:.2f}")
elif current_price < last_price:
send_notification(product_name, last_price, current_price)
elif current_price > last_price:
print(f"Price for {product_name} increased to ${current_price:.2f}")
else:
print(f"Price for {product_name} remains ${current_price:.2f}")
stored_prices[product_url] = current_price # Update price
if __name__ == "__main__":
# Simulate stored prices (from a file in a real app)
my_tracked_items = {
"https://example.com/gadget": 200.00, # Initial price
"https://example.com/widget": 50.00
}
print("--- First Run ---")
check_price("https://example.com/gadget", "Cool Gadget", my_tracked_items)
check_price("https://example.com/widget", "Awesome Widget", my_tracked_items)
print("\n--- Second Run ---")
check_price("https://example.com/gadget", "Cool Gadget", my_tracked_items)
check_price("https://example.com/widget", "Awesome Widget", my_tracked_items)
print("\nFinal tracked prices:", json.dumps(my_tracked_items, indent=2))Price Logic Check
Consider a price tracker bot. It last recorded a product price of $50.00. On its next run, it fetches the price as $45.00. What should the bot do?
Recap & Next Steps
You've learned the fundamental steps to build a price tracker bot!
- Fetch HTML with
requests. - Parse prices with
BeautifulSoup. - Store prices (e.g., in a JSON file).
- Compare current vs. stored prices.
- Notify on price drops.
Next steps include scheduling your bot to run automatically and exploring more advanced notification methods.
คำถามที่พบบ่อย
บทเรียน “สร้างบอตติดตามราคา” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “สร้างบอตติดตามราคา” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Web Scraping & Bots ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Web Scraping & Bots มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “สร้างบอตติดตามราคา”
พัฒนาบอตที่ตรวจสอบราคาสินค้าบนเว็บไซต์อีคอมเมิร์ซและส่งการแจ้งเตือนเมื่อราคาลดลง คุณปฏิบัติ Web Scraping & Bots ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Web Scraping & Bots หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Web Scraping & Bots บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “สร้างบอตติดตามราคา” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Web Scraping & Bots นี้ได้ไหม
ได้ บทเรียน Web Scraping & Bots ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- สร้างบอตติดตามราคา
- สร้างเครื่องมือติดตามโซเชียลมีเดีย
- นำบอตขึ้นแพลตฟอร์มคลาวด์
- การส่งสัญญาณเตือนและการแจ้งเตือน