使用 Python 中的网页抓取比较两个在线超市的价格

问题描述 投票:0回答:1

我正在开发一个程序,使用 Python 比较两个在线超市的类似产品的价格。我有两个代表每个供应商的产品页面的 URL,我需要提取并比较给定产品的价格。 网址是- smiles_coconut = 'https://scrape-sm1.github.io/site1/COCONUT%20market1super.html' glomark_coconut = 'https://glomark.lk/coconut/p/11624'

我已经开始研究compare_prices函数,但我在提取和比较价格方面面临一些挑战。我将不胜感激对现有代码的任何指导或改进。

我尝试通过检查 HTML 页面的结构并使用网络抓取技术来实现 Compare_prices 函数。我希望该函数能够正确提取并比较给定产品的价格

python html web-scraping beautifulsoup python-requests
1个回答
0
投票

您可以使用 BeautifulSoup 和 requests 等库来获取和解析产品页面的 HTML 内容。以下是使用这些库的 Compare_prices 函数的示例实现:

import requests
from bs4 import BeautifulSoup

def get_price(url):
    # Send a GET request to the URL
    response = requests.get(url)
    
    # Check if the request was successful
    if response.status_code == 200:
        # Parse the HTML content of the page
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Find the element containing the price
        price_element = soup.find('span', class_='price')  # Adjust this according to the structure of the page
        
        # Extract the price text
        if price_element:
            price_text = price_element.text.strip()
            # Some cleaning of the price text, e.g., removing currency symbols
            # You may need to customize this part based on the structure of the page
            price_text = price_text.replace('Rs', '').replace(',', '').strip()
            return float(price_text)  # Convert the price to a float
    else:
        print("Failed to fetch page:", url)
    return None

def compare_prices(url1, url2):
    price1 = get_price(url1)
    price2 = get_price(url2)
    
    if price1 is not None and price2 is not None:
        if price1 < price2:
            print("Product from laughs_coconut is cheaper.")
        elif price1 > price2:
            print("Product from glomark_coconut is cheaper.")
        else:
            print("Prices are the same.")
    else:
        print("Unable to compare prices.")

# URLs of the product pages
laughs_coconut = 'https://scrape-sm1.github.io/site1/COCONUT%20market1super.html'
glomark_coconut = 'https://glomark.lk/coconut/p/11624'

# Compare prices
compare_prices(laughs_coconut, glomark_coconut)
  • get_price 函数从给定的 URL 获取 HTML 内容,然后使用 BeautifulSoup 解析内容并提取价格信息。您可能需要根据产品页面上的 HTML 结构调整 find 方法参数。

  • compare_prices 函数使用 get_price 函数从两个 URL 检索价格,然后比较它们。

确保使代码适应您正在处理的 HTML 页面的实际结构。您可能需要检查产品页面的 HTML 结构,以确定查找和提取价格信息的适当方法。

© www.soinside.com 2019 - 2024. All rights reserved.