Hyrje

Në këtë postim në blog, ne do të kalojmë procesin e nxjerrjes së të dhënave të produktit nga The Home Depot duke përdorur API Home Depot Product dhe gjuhën e programimit Python.

Për të nxjerrë me sukses rezultatet e produktit Home Depot, do t'ju duhet të kaloni parametrin product_id, ky parametër është përgjegjës për një produkt specifik. Ju mund ta nxirrni këtë parametër nga rezultatet e kërkimit. Hidhini një sy postimit në blog Integroni të dhënat e rezultateve të faqes së kërkimit të depove kryesore me SerpApi dhe Python, në të cilin përshkrova në detaje se si të nxirren të gjitha të dhënat e nevojshme.

Ju mund të shikoni kodin e plotë në IDE në internet (Replit).

Nëse preferoni formatin e videos, ne kemi një video të dedikuar që tregon se si ta bëni këtë: API i produktit Home Depot — SerpApi.

Çfarë do të gërvishtet

Pse të përdorni API?

Ka disa arsye që mund të përdorin API, e jona në veçanti:

  • Nuk ka nevojë të krijoni një analizues nga e para dhe ta mirëmbani atë.
  • Anashkaloni blloqet nga Google: zgjidhni CAPTCHA ose zgjidhni blloqe IP.
  • Paguani për përfaqësuesit dhe zgjidhësit CAPTCHA.
  • Nuk keni nevojë të përdorni automatizimin e shfletuesit.

SerpApi trajton gjithçka në backend me kohë përgjigjeje të shpejta nën ~ 2,5 sekonda (~ 1,2 sekonda me shpejtësi qesharake) për kërkesë dhe pa automatizimin e shfletuesit, i cili bëhet shumë më i shpejtë. Kohët e përgjigjes dhe normat e statusit tregohen në faqen e statusit të SerpApi.

Kodi i plotë

Ky kod merr të gjitha të dhënat për secilin prej 24 produkteve në faqen e parë:

from serpapi import GoogleSearch
import json

params = {
    'api_key': '...',           # https://serpapi.com/manage-api-key
    'engine': 'home_depot',     # SerpApi search engine 
    'q': 'coffee maker',        # query
}

search = GoogleSearch(params)   # where data extraction happens on the SerpApi backend
results = search.get_dict()     # JSON -> Python dict

product_ids = [result['product_id'] for result in results['products']]

home_depot_products = []

for product_id in product_ids:
    product_params = {
        'api_key': '...',                   # https://serpapi.com/manage-api-key
        'engine': 'home_depot_product',     # SerpApi search engine 
        'product_id': product_id,           # HomeDepot ID of a product
    }

    product_search = GoogleSearch(product_params)
    product_results = product_search.get_dict()

    home_depot_products.append(product_results['product_results'])

print(json.dumps(home_depot_products, indent=2, ensure_ascii=False))

Përgatitja

Instaloni bibliotekën:

pip install google-search-results

google-search-results është një paketë API SerpApi.

Shpjegimi i kodit

Importoni biblioteka:

from serpapi import GoogleSearch
import json
  • GoogleSearchpër të gërvishtur dhe analizuar rezultatet e Google duke përdorur bibliotekën e skrapimit të uebit SerpApi.
  • jsonpër të konvertuar të dhënat e nxjerra në një objekt JSON.

Në fillim të kodit, duhet të bëni kërkesën për të marrë rezultatet e kërkimit. Pastaj product_id do të nxirret prej tyre.

Parametrat janë përcaktuar për gjenerimin e URL-së. Nëse dëshironi të kaloni parametra të tjerë në URL, mund ta bëni këtë duke përdorur fjalorin params:

params = {
    'api_key': '...',           # https://serpapi.com/manage-api-key
    'engine': 'home_depot',     # SerpApi search engine 
    'q': 'coffee maker',        # query
}

Më pas, ne krijojmë një objekt search ku të dhënat merren nga fundi i SerpApi. Në fjalorin results ne marrim të dhëna nga JSON:

search = GoogleSearch(params)   # data extraction on the SerpApi backend
results = search.get_dict()     # JSON -> Python dict

Për momentin, 24 rezultatet e para të kërkimit nga faqja e parë ruhen në fjalorin results. Nëse jeni të interesuar për të gjitha rezultatet e kërkimit me faqe, atëherë shikoni postimin në blog Përdorimi i API-së së produktit të depove shtëpiake nga SerpApi.

Lista product_ids ruan product_id të cilat janë nxjerrë nga çdo rezultat kërkimi. Këto të dhëna do të nevojiten më vonë:

product_ids = [result['product_id'] for result in results['products']]

Deklarimi i listës home_depot_products ku do të shtohen të dhënat e nxjerra:

home_depot_products = []

Më pas, duhet të hyni veçmas në secilën faqe të produktit duke përsëritur listën product_ids:

for product_id in product_ids:
    # data extraction will be here

Këta parametra janë përcaktuar për gjenerimin e URL-së rreth produktit. Nëse dëshironi të kaloni parametra të tjerë në URL, mund ta bëni këtë duke përdorur fjalorin product_params:

product_params = {
    'api_key': '...',                   # https://serpapi.com/manage-api-key
    'engine': 'home_depot_product',     # SerpApi search engine 
    'product_id': product_id,           # HomeDepot ID of a product
}
  • api_keyParametri përcakton çelësin privat SerpApi për t'u përdorur. Mund ta gjeni nën llogaria juaj -› Çelësi API
  • engineVendosni parametrin në home_depot_product për të përdorur motorin API të produktit Home Depot.
  • product_idIdentifikuesi HomeDepot i një produkti.

📌Shënim: Ju gjithashtu mund të shtoni "Parametra API" të tjerë.

Më pas, ne krijojmë një objekt product_search ku të dhënat merren nga fundi i SerpApi. Në fjalorin product_results ne marrim një paketë të re të të dhënave në formatin JSON:

product_search = GoogleSearch(product_params)
product_results = product_search.get_dict()

Shtimi i të dhënave për produktin aktual në listën home_depot_products:

home_depot_products.append(product_results['product_results'])
# title = product_results['product_results']['title']
# description = product_results['product_results']['description']
# rating = product_results['product_results']['rating']
# reviews = product_results['product_results']['reviews']
# price = product_results['product_results']['price']

📌Shënim: Në komentet e mësipërme, kam treguar se si të nxjerrim fusha specifike nga produkti aktual.

Pasi të merren të gjitha të dhënat, ato nxirren në formatin JSON:

print(json.dumps(home_depot_products, indent=2, ensure_ascii=False))

Prodhimi

[
  {
    "product_id": "206667220",
    "title": "12-Cup Programmable Stainless Steel Drip Coffee Maker with Thermal Carafe",
    "description": "Get your fix throughout the day with the BLACK+DECKER CM2035B 12-Cup Thermal Coffeemaker. The stainless steel thermal carafe is vacuum-sealed to ensure your coffee stays at the optimal drinking temperature for hours and the Perfect Pour spout does away with spills and drips. The easy-to-use digital controls include a setting for batches of 1-4 cups BLACK+DECKER and the BLACK+DECKER logo are trademarks of The Black and Decker Corporation and are used under license. Cup equals approximately 5 oz. (varies by brewing technique).",
    "link": "https://www.homedepot.com/p/BLACK-DECKER-12-Cup-Programmable-Stainless-Steel-Drip-Coffee-Maker-with-Thermal-Carafe-CM2035B/206667220",
    "upc": "050875812123",
    "model_number": "CM2035B",
    "favorite": 103,
    "rating": "3.1793",
    "reviews": "569",
    "price": 69.73,
    "highlights": [
      "Electric drip-type coffee maker for creating delectable coffee",
      "Serves up to 12 cups with ease",
      "Includes an Evenstream shower head for maximum flavor extraction",
      "Made from stainless steel for high longevity and durability",
      "Provides a flavorful pot of hot coffee"
    ],
    "brand": {
      "name": "BLACK+DECKER",
      "link": "https://www.homedepot.com/b/Appliances-Small-Kitchen-Appliances-Coffee-Makers-Drip-Coffee-Makers/BLACK-DECKER/N-5yc1vZ2fkp8ffZe7c"
    },
    "images": [
      [
        "https://images.thdstatic.com/productImages/22b7e43f-06ea-497b-9d9e-c2c4d23dbd42/svn/black-with-stainless-steel-black-decker-drip-coffee-makers-cm2035b-64_65.jpg",
        "https://images.thdstatic.com/productImages/22b7e43f-06ea-497b-9d9e-c2c4d23dbd42/svn/black-with-stainless-steel-black-decker-drip-coffee-makers-cm2035b-64_100.jpg",
        "https://images.thdstatic.com/productImages/22b7e43f-06ea-497b-9d9e-c2c4d23dbd42/svn/black-with-stainless-steel-black-decker-drip-coffee-makers-cm2035b-64_145.jpg",
        "https://images.thdstatic.com/productImages/22b7e43f-06ea-497b-9d9e-c2c4d23dbd42/svn/black-with-stainless-steel-black-decker-drip-coffee-makers-cm2035b-64_300.jpg",
        "https://images.thdstatic.com/productImages/22b7e43f-06ea-497b-9d9e-c2c4d23dbd42/svn/black-with-stainless-steel-black-decker-drip-coffee-makers-cm2035b-64_400.jpg",
        "https://images.thdstatic.com/productImages/22b7e43f-06ea-497b-9d9e-c2c4d23dbd42/svn/black-with-stainless-steel-black-decker-drip-coffee-makers-cm2035b-64_600.jpg",
        "https://images.thdstatic.com/productImages/22b7e43f-06ea-497b-9d9e-c2c4d23dbd42/svn/black-with-stainless-steel-black-decker-drip-coffee-makers-cm2035b-64_1000.jpg"
      ],
      ... other images
    ],
    "bullets": [
      "12-cup thermal carafe - the large capacity carafe is double-walled and vacuum-sealed to keep your coffee at optimal drinking temperature for hours",
      "Customizable brewing options - drink your favorite coffee every morning using features like the brew strength selector and the option for small-batch (1-4 cup) brewing that maintains all the flavor of a full brew",
      "even stream showerhead - the Evenstream Showerhead dispenses water evenly over the packed coffee, extracting maximum flavor and wasting less",
      "No-drip perfect pour spout - don't put up with annoying spills, the carafe spout is designed to prevent spills and drips while pouring",
      "Wide-mouth carafe opening-the carafe is designed with a wide opening for fast, easy cleanup with a damp towel",
      "<a href=https://www.homedepot.com/c/electronics_recycling_programs style=color:#F96302; target=_blank>Click here for more information on Electronic Recycling Programs</a>"
    ],
    "info_and_guides": [
      {
        "title": "Warranty",
        "link": "https://images.thdstatic.com/catalog/pdfImages/de/deb8e49b-76c5-4dd2-82e0-6863ebb8408c.pdf"
      },
      {
        "title": "Use and Care Manual",
        "link": "https://images.thdstatic.com/catalog/pdfImages/68/681b462d-4233-4d43-ab88-ce5dc12ff487.pdf"
      }
    ],
    "specifications": [
      {
        "key": "Details",
        "value": [
          {
            "name": "Appliance Type",
            "value": "Coffee Maker"
          },
          ... other results
        ]
      },
      {
        "key": "Warranty / Certifications",
        "value": [
          {
            "name": "Certifications and Listings",
            "value": "ETL Listed"
          },
          ... other results
        ]
      },
      {
        "key": "Dimensions",
        "value": [
          {
            "name": "Product Depth (in.)",
            "value": "8.58"
          },
          ... other results
        ]
      }
    ]
  },
  ... other products
]

📌Shënim: Drejtohuni në "sheshin e lojërave" për një demo live dhe interaktive.

Lidhjet

Botuar fillimisht në SerpApi: https://serpapi.com/blog/using-the-home-depot-product-api-from-serpapi/

Bashkohuni me ne në Twitter | "YouTube"

Shto një "Kërkesë për veçori"💫 ose një "Bug"🐞