File size: 6,505 Bytes
7a511b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
from playwright.sync_api import sync_playwright
import urllib.parse


def scrape_hificorp(page, product_name: str) -> dict | None:
    """
    Scrape HiFiCorp for the given product_name.
    Returns a dict with keys: title, normal_price, promotion_price, source, product_link
    or None if no product found.
    """
    search_url = (
        "https://www.hificorp.co.za/catalogsearch/result/?q="
        + urllib.parse.quote_plus(product_name)
    )
    page.goto(search_url, timeout=120_000)
    page.wait_for_selector(".product-item-link", timeout=60_000)

    product_url = page.locator(
        ".product-item-link").first.get_attribute("href")
    if not product_url:
        return None

    page.goto(product_url, timeout=120_000)
    page.wait_for_selector("h1.page-title", timeout=60_000)

    title = page.locator("h1.page-title").inner_text().strip()

    # Promotion (final) price
    try:
        promotion_price = (
            page.locator('[data-price-type="finalPrice"] .price')
            .first.inner_text()
            .strip()
        )
    except Exception:
        promotion_price = None

    # Old (normal) price, if present
    try:
        old_nodes = page.locator('[data-price-type="oldPrice"] .price')
        normal_price = (
            old_nodes.first.inner_text().strip() if old_nodes.count() else None
        )
    except Exception:
        normal_price = None

    # Fallback if no old price
    normal_price = normal_price or promotion_price

    return {
        "title": title,
        "normal_price": normal_price,
        "promotion_price": promotion_price,
        "source": "HiFiCorp",
        "product_link": product_url,
    }


def scrape_incredible(page, product_name: str) -> dict | None:
    """
    Scrape Incredible Connection for the given product_name.
    Returns a dict with keys: title, normal_price, promotion_price, source, product_link
    or None if no product found.
    """
    search_url = (
        "https://www.incredible.co.za/catalogsearch/result/?q="
        + urllib.parse.quote_plus(product_name)
    )
    page.goto(search_url, timeout=120_000)
    page.wait_for_selector(".product-item-link", timeout=60_000)

    product_url = page.locator(
        ".product-item-link").first.get_attribute("href")
    if not product_url:
        return None

    page.goto(product_url, timeout=120_000)
    page.wait_for_selector("h1.page-title", timeout=60_000)

    title = page.locator("h1.page-title").inner_text().strip()

    try:
        promotion_price = (
            page.locator('[data-price-type="finalPrice"] .price')
            .first.inner_text()
            .strip()
        )
    except Exception:
        promotion_price = None

    try:
        old_nodes = page.locator('[data-price-type="oldPrice"] .price')
        normal_price = (
            old_nodes.first.inner_text().strip() if old_nodes.count() else None
        )
    except Exception:
        normal_price = None

    normal_price = normal_price or promotion_price

    return {
        "title": title,
        "normal_price": normal_price,
        "promotion_price": promotion_price,
        "source": "Incredible Connection",
        "product_link": product_url,
    }


def search_product(product_name: str) -> list[dict]:
    """
    Uses Playwright to scrape HiFiCorp and Incredible Connection for product_name.
    Returns a list of dictionaries, each dict with keys:
      title, normal_price, promotion_price, source, product_link.

    If Playwright cannot run or no products found, returns an empty list.
    """
    results = []

    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(
                headless=True,
                args=["--no-sandbox", "--disable-setuid-sandbox",
                      "--disable-dev-shm-usage"],
            )
            page = browser.new_page()

            # Scrape HiFiCorp
            try:
                hifi_data = scrape_hificorp(page, product_name)
                if hifi_data:
                    results.append(hifi_data)
            except Exception as e:
                return (r"HiFiCorp scraping error:", type(e).__name__, e)
            browser.close()

    except NotImplementedError:
        # Playwright cannot launch a browser in this environment
        return ("Playwright NotImplementedError: scraping skipped.")

    except Exception as e:
        # Any other Playwright/browser launch error
        print("Playwright launch error:", type(e).__name__, e)
        return []

    return results


def get_scraped_product_data(product_name: str):
    """
    Wrapper function to search for product data.
    Returns a list of dictionaries with product details.
    """
    if not product_name:
        return []

    results = search_product(product_name)

    # def save_df_to_csv(df: pd.DataFrame, filename="shop_out_results.csv"):
    results.to_csv("scraped.csv", index=False)

    if not results:
        return []

    return results


def search_your_product(query: str):
    """Search for a product using the provided query string."""

    json_out = search_product(query)
    if not json_out:
        return "No results found."
    else:
        product = []
        for item in json_out:
            product.append({
                "title": item["title"],
                "normal_price": item["normal_price"],
                "promotion_price": item["promotion_price"],
                "source": item["source"],
                "product_link": item["product_link"]
            })

    return product


# For debugging or manual runs:
if __name__ == "__main__":
    query = input("Enter product name: ")
    json_out = search_product(query)
    if not json_out:
        print("No results found.")
    else:
        product = []
        for item in json_out:
            product.append({
                "title": item["title"],
                "normal_price": item["normal_price"],
                "promotion_price": item["promotion_price"],
                "source": item["source"],
                "product_link": item["product_link"]
            })

    for items in product:
        print(f"Title: {items['title']}")
        print(f"Normal Price: {items['normal_price']}")
        print(f"Promotion Price: {items['promotion_price']}")
        print(f"Source: {items['source']}")
        print(f"Product Link: {items['product_link']}")
        print("-" * 40)
    print(f"Found {len(product)} results for '{query}'.")
    print("Search complete!")