Skip to content

Commit

Permalink
simplify product price flow (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
shuhaodo authored Aug 20, 2024
1 parent 4515fe2 commit 7133b86
Showing 1 changed file with 13 additions and 22 deletions.
35 changes: 13 additions & 22 deletions examples/compare_product_prices/async_compare_product_prices.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

# Set the URL to the desired website
BESTBUY_URL = "https://www.bestbuy.com"
TELQUEST_URL = "https://www.telquestintl.com"
EBAY_URL = "https://www.ebay.com"
TELQUEST_URL = "https://www.telquestintl.com"

# Define the queries to interact with the page
HOME_PAGE_QUERY = """
Expand All @@ -18,37 +18,28 @@
}
"""

PRODUCT_PAGE_QUERY = """
{
nintendo_switch_oled_model_white
}
"""

PRODUCT_INFO_QUERY = """
{
nintendo_switch_price
product_price (for Nintendo Switch - OLed Model - w/ White Joy-Con)
}
"""


async def fetch_price(context: BrowserContext, session_url, query):
async def fetch_price(context: BrowserContext, session_url):
"""Open the given URL in a new tab and fetch the price of the product."""
# Create a page in a new tab in the broswer context and wrap it to get access to the AgentQL's querying API
page = await agentql.wrap_async(context.new_page())
await page.goto(session_url)

# Search for the product
await page.wait_for_page_ready_state()
home_response = await page.query_elements(HOME_PAGE_QUERY)
await home_response.search_input.fill("Nintendo Switch - OLED Model White")
await home_response.search_button.click()

# Click on product link
product_page_response = await page.query_elements(PRODUCT_PAGE_QUERY)
await product_page_response.nintendo_switch_oled_model_white.click()

# Fetch the price data from the page
data = await page.query_data(query)
return data["nintendo_switch_price"]
data = await page.query_data(PRODUCT_INFO_QUERY)
return data["product_price"]


async def get_price_across_websites():
Expand All @@ -57,17 +48,17 @@ async def get_price_across_websites():
headless=False
) as browser, await browser.new_context() as context:
# Open multiple tabs in the same browser context to fetch prices concurrently
bestbuy_price, ebay_price, telquest_price = await asyncio.gather(
fetch_price(context, BESTBUY_URL, PRODUCT_INFO_QUERY),
fetch_price(context, EBAY_URL, PRODUCT_INFO_QUERY),
fetch_price(context, TELQUEST_URL, PRODUCT_INFO_QUERY),
(bestbuy_price, ebay_price, telquest_price) = await asyncio.gather(
fetch_price(context, BESTBUY_URL),
fetch_price(context, EBAY_URL),
fetch_price(context, TELQUEST_URL),
)

print(
f"""
Price at BestBuy: ${bestbuy_price}
Price at Ebay: ${ebay_price}
Price at Telquest: ${telquest_price}
Price at BestBuy: {bestbuy_price}
Price at Target: {ebay_price}
Price at Telquest: {telquest_price}
"""
)

Expand Down

0 comments on commit 7133b86

Please sign in to comment.