# 7.2 PChome 24h API爬蟲

PChome 24h有提供API, 所以就不用爬網頁了.

```python
import html
import urllib.parse
import time
import json
import requests
import os
from requests.adapters import HTTPAdapter


STORE = 'pchome'
SESSION_TIMEOUT = 3
SESSION_MAX_RETRIES = 3
PCHOME_API_ENDPOINT = 'http://ecshweb.pchome.com.tw/search/v3.3/all/results?q=%s&sort=rnk&price=%s-%s'
PCHOME_PRODUCT_URL_PREFIX = 'http://24h.pchome.com.tw/prod/'
PCHOME_IMG_URL_PREFIX = 'http://ec1img.pchome.com.tw/'


def get_web_content(query_url):
    session = requests.Session()
    session.mount(query_url, HTTPAdapter(max_retries=SESSION_MAX_RETRIES))
    try:
        # The timeout unit is second.
        resp = session.get(query_url, timeout=SESSION_TIMEOUT)
    except requests.exceptions.RequestException as e:
        print(e)
        return None
    return resp


def collect_items(raw_data):
    extracted_items = list()
    raw_items = raw_data['prods']
    for raw_item in raw_items:
        try:
            item = dict()
            item['name'] = html.unescape(raw_item['name'])
            item['price'] = int(raw_item['price'])
            item['describe'] = raw_item['describe']
            item['img_url'] = PCHOME_IMG_URL_PREFIX + raw_item['picB']
            item['url'] = PCHOME_PRODUCT_URL_PREFIX + raw_item['Id']
            extracted_items.append(item)
        except Exception:
            pass
    return extracted_items


def search_pchome(query, min_price, max_price):
    query = urllib.parse.quote(query)
    query_url = PCHOME_API_ENDPOINT % (query, str(min_price), str(max_price))
    resp = get_web_content(query_url)
    if not resp:
        return []

    resp.encoding = 'UTF-8'
    data = resp.json()
    if data['prods'] is None:
        return []

    total_page_count = int(data['totalPage'])
    if total_page_count == 1:
        return collect_items(data)

    urls = []
    current_page = 1
    while current_page <= total_page_count:
        current_page_url = query_url + '&page=' + str(current_page)
        urls.append(current_page_url)
        current_page += 1

    items = []
    for url in urls:
        resp = get_web_content(url)
        if resp:
            resp.encoding = 'UTF-8'
            items += collect_items(resp.json())
    return items


def save_search_result(data):
    with open(os.path.join('json', data['date'] + '-%s.json' % STORE), 'w', encoding='UTF-8') as file:
        json.dump(data, file, indent=2, ensure_ascii=False)


def main():
    query_str = 'iphone 7 128g plus'
    min_price = 20000
    max_price = 40000
    items = search_pchome(query_str, min_price, max_price)
    today = time.strftime('%m-%d')
    print('Search item \'%s\' from %s...' % (query_str, STORE))
    print('Search %d records on %s' % (len(items), today))
    for item in items:
        print(item)
    data = {
        'date': today,
        'store': STORE,
        'items': items
    }

    save_search_result(data)


if __name__ == '__main__':
    main()
```

輸出結果:

```javascript
/Users/Carl/work/Project/python-crawler/env/web-crawler/bin/python /Users/Carl/work/Project/python-crawler/web-crawler-practice/007/pchome_crawler.py
Search item 'iphone 7 128g plus' from pchome...
Search 39 records on 05-27
{'name': '[福利品] Apple iPhone 7 Plus (128G)', 'price': 26490, 'describe': '限時特價*優質福利品下殺*[福利品]Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007VSRG/000001_1491883229.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007VSRG'}
{'name': 'Apple iPhone 7 Plus (128G)-紅色', 'price': 30268, 'describe': 'RED★下殺超低價Apple iPhone 7 Plus (128G)-RED', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86190084M4I/000001_1495098016.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-190084M4I'}
{'name': 'Apple iPhone 7 Plus (128G)-玫瑰金', 'price': 30990, 'describe': '玫瑰金★下殺超低價Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86190084LVH/000001_1495104273.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-190084LVH'}
{'name': 'Apple iPhone 7 Plus (128G)-曜石黑', 'price': 30268, 'describe': '曜石黑★送玻璃貼+保殼Apple iPhone 7 Plus (128G) 曜石黑', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007P24T/000001_1494818678.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007P24T'}
{'name': 'Apple iPhone 7 Plus (128G)', 'price': 30990, 'describe': '黑|銀|金★熱銷機下殺Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007MKVF/000001_1495104459.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007MKVF'}
{'name': 'Apple iPhone 7 Plus (128G)-紅色', 'price': 30990, 'describe': '★送MFi傳輸線★Apple iPhone 7 Plus (128G)-RED', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A90080ZVJ/000001_1491823974.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A90080ZVJ'}
{'name': 'Apple iPhone 7 Plus (128G)', 'price': 30990, 'describe': '五色★下殺超低價Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007IBEX/000001_1487643804.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007IBEX'}
{'name': '\tApple iPhone 7 Plus (128G)-曜石黑(MN4V2TA/A)', 'price': 30990, 'describe': '曜石黑★送傳輸線+玻璃貼+保殼Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86190082JNZ/000001_1494814009.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-190082JNZ'}
{'name': '(福利品)Apple iPhone 7 PLUS (128G)', 'price': 27990, 'describe': '(福利品)★保固至2018年1月Apple iPhone 7 PLUS (128G)', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007Z1MV/000001_1489737354.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007Z1MV'}
{'name': '\tApple iPhone 7 Plus (128G)-消光黑(MN4M2TA/A)', 'price': 30990, 'describe': '消光黑★熱銷機送保殼+保貼Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ861900802CH/000001_1495012595.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-1900802CH'}
{'name': 'Apple iPhone 7 Plus (128G)', 'price': 32900, 'describe': '消光黑★送MFi傳輸線Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ81A9007I9J9/000001_1495097910.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ81-A9007I9J9'}
{'name': 'Apple iPhone 7 Plus 128G 福利品 ', 'price': 28690, 'describe': 'Apple iPhone 7 Plus 128G 福利品 ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ8IA9007QRY1/000001_1482123663.png', 'url': 'http://24h.pchome.com.tw/prod/DYAJ8I-A9007QRY1'}
{'name': 'Apple iPhone 7 Plus (128G)-紅色', 'price': 31900, 'describe': '原價$32900★現降$1000★Apple iPhone 7 Plus (128G)-RED', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007ZURE/000001_1490596607.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007ZURE'}
{'name': 'Apple iPhone 7 Plus (128G)曜石黑', 'price': 32500, 'describe': '★行電萬用週邊組!!★Apple iPhone 7 Plus (128G) 智慧型手機-曜石黑 ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007L0C8/000001_1477276720.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007L0C8'}
{'name': 'Apple iPhone 7 Plus (128G)', 'price': 30990, 'describe': '送保貼+空壓殼+拭淨布Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007JVZD/000001_1477964391.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007JVZD'}
{'name': 'Apple iPhone 7 Plus (128G)-銀(MN4P2TA/A)', 'price': 30990, 'describe': '銀色★送玻璃貼+保殼Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ8619008266Z/000001_1495012534.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-19008266Z'}
{'name': 'Apple iPhone 7 Plus (128G)-曜石黑', 'price': 30990, 'describe': '曜石黑★送Lightning風扇+空壓殼+保護貼+拭淨布Apple iPhone 7 Plus (128G) 曜石黑', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007N3VN/000001_1478762751.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007N3VN'}
{'name': 'Apple iPhone 7 Plus 128G 福利品', 'price': 28990, 'describe': 'Apple iPhone 7 Plus 128G 福利品', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007O2LA/000001_1479710767.png', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007O2LA'}
{'name': 'Apple iPhone 7 Plus (128G)★', 'price': 31900, 'describe': '霧黑★送64G OTG碟+MFI線材+玻璃貼+背蓋Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007IDQW/000001_1478549206.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007IDQW'}
{'name': 'iPhone 7 Plus(128G)+搭配台灣之星攜碼599專案@121919@4G_勁速_虛擬經銷獨家599_30M@預繳6000', 'price': 24999, 'describe': '搭台灣之星攜碼599專案iPhone 7 Plus(128G)', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAS0719008429V/000001_1494577597.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAS07-19008429V'}
{'name': 'Apple iPhone 7 Plus (128G) RED 紅色', 'price': 31900, 'describe': '【~~~現貨不用等~~~】Apple iPhone 7 Plus (128G) RED 紅色', 'img_url': 'http://ec1img.pchome.com.tw//items/QAAN22A9007ZVVV/000001_1490609939.jpg', 'url': 'http://24h.pchome.com.tw/prod/QAAN22-A9007ZVVV'}
{'name': 'Apple iPhone 7 Plus (128G)', 'price': 31990, 'describe': '四色★現貨供應 贈玻璃貼+空壓殼+自拍棒 Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007KOI7/000001_1477274845.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007KOI7'}
{'name': 'Apple iPhone 7 Plus (128G)', 'price': 31999, 'describe': '五色★下殺超低價Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007WP1A/000001_1487417462.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007WP1A'}
{'name': 'Apple iPhone 7 Plus (128G)-玫瑰金', 'price': 30990, 'describe': '玫瑰金★下殺超低價Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A90084VUA/000001_1495431910.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A90084VUA'}
{'name': 'Apple iPhone 7 Plus (128G)-消光黑(MN4M2TA/A)', 'price': 26450, 'describe': 'Apple iPhone 7 Plus (128G) -消光黑', 'img_url': 'http://ec1img.pchome.com.tw//items/DGAV0MA90085B8Q/000001_1495786178.jpg', 'url': 'http://24h.pchome.com.tw/prod/DGAV0M-A90085B8Q'}
{'name': 'Apple iPhone 7 Plus (128G)-消光黑', 'price': 30990, 'describe': '消光黑★送玻璃貼+保殼Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A90084Z4A/000001_1495513913.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A90084Z4A'}
{'name': 'iPhone 7 Plus(128G)-紅+搭配台灣之星攜碼599專案@121919@4G_勁速_虛擬經銷獨家599_30M@預繳6000', 'price': 25990, 'describe': '搭台灣之星攜碼599專案iPhone 7 Plus(128G)-紅', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAS071900858F1/000001_1495704724.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAS07-1900858F1'}
{'name': 'Apple iPhone 7 Plus (128G)-紅色(MPQW2TA/A)', 'price': 27241, 'describe': 'Apple iPhone 7 Plus (128G)-紅', 'img_url': 'http://ec1img.pchome.com.tw//items/DGAV0MA90085B8M/000001_1495786569.jpg', 'url': 'http://24h.pchome.com.tw/prod/DGAV0M-A90085B8M'}
{'name': 'Apple iPhone 7 Plus (128G)', 'price': 31500, 'describe': '銀色★送保殼+玻璃貼Apple iPhone 7 Plus (128G) ', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007LCZ7/000001_1476958636.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007LCZ7'}
{'name': 'Apple iPhone 7 Plus (128G)-曜石黑', 'price': 31990, 'describe': '曜石黑★加贈藍芽耳機,玻璃貼,空壓殼Apple iPhone 7 Plus (128G) 曜石黑', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAJ86A9007KOJR/000001_1477567756.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAJ86-A9007KOJR'}
{'name': 'Apple iPhone 7 Plus (128G)-紅色(MPQW2TA/A)', 'price': 27241, 'describe': 'Apple iPhone 7 Plus (128G)-紅', 'img_url': 'http://ec1img.pchome.com.tw//items/DGAV0MA90085B8N/000001_1495786683.jpg', 'url': 'http://24h.pchome.com.tw/prod/DGAV0M-A90085B8N'}
{'name': 'Apple iPhone 7 Plus (128G)-紅色(MPQW2TA/A)', 'price': 27241, 'describe': 'Apple iPhone 7 Plus (128G)-紅', 'img_url': 'http://ec1img.pchome.com.tw//items/DGAV0MA90085B8L/000001_1495786468.jpg', 'url': 'http://24h.pchome.com.tw/prod/DGAV0M-A90085B8L'}
{'name': 'Apple iPhone 7 Plus (128G)-曜石黑(MN4V2TA/A)', 'price': 26450, 'describe': 'Apple iPhone 7 Plus (128G) 曜石黑', 'img_url': 'http://ec1img.pchome.com.tw//items/DGAV0MA90085B8S/000001_1495785791.jpg', 'url': 'http://24h.pchome.com.tw/prod/DGAV0M-A90085B8S'}
{'name': 'iPhone 7 Plus(128G)-紅+搭配台灣之星攜碼799專案@120557@4G_勁速_799專案_30M@預繳7000', 'price': 22990, 'describe': '搭台灣之星攜碼799專案iPhone 7 Plus(128G)-紅', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAS071900858G3/000001_1495704692.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAS07-1900858G3'}
{'name': 'Apple iPhone 7 Plus (128G)-曜石黑(MN4V2TA/A)', 'price': 26450, 'describe': 'Apple iPhone 7 Plus (128G)- 曜石黑', 'img_url': 'http://ec1img.pchome.com.tw//items/DGAV0MA90085B8R/000001_1495785999.jpg', 'url': 'http://24h.pchome.com.tw/prod/DGAV0M-A90085B8R'}
{'name': 'Apple iPhone 7 Plus 128G 5.5吋智慧型手機', 'price': 34508, 'describe': '好禮大放送Apple iPhone 7 Plus 128G 5.5吋智慧型手機', 'img_url': 'http://ec1img.pchome.com.tw//items/QAANALA9007SDLU/000001_1483603657.jpg', 'url': 'http://24h.pchome.com.tw/prod/QAANAL-A9007SDLU'}
{'name': 'iPhone 7 Plus(128G)+搭配台灣之星攜碼799專案@120557@4G_勁速_799專案_30M@預繳7000', 'price': 21990, 'describe': '搭台灣之星攜碼799專案iPhone 7 Plus(128G)', 'img_url': 'http://ec1img.pchome.com.tw//items/DYAS0719008427O/000001_1494577543.jpg', 'url': 'http://24h.pchome.com.tw/prod/DYAS07-19008427O'}
{'name': '[福利品] Apple iPhone 7 Plus (128G)', 'price': 28800, 'describe': '送玻璃保貼+保護套[福利品] Apple iPhone 7 Plus (128G)', 'img_url': 'http://ec1img.pchome.com.tw//items/QAAN5GA9007OHUR/000001_1480045535.jpg', 'url': 'http://24h.pchome.com.tw/prod/QAAN5G-A9007OHUR'}
{'name': 'Apple iPhone 7 128G 4.7吋智慧型手機', 'price': 29610, 'describe': '好禮大放送Apple iPhone 7 128G 4.7吋智慧型手機', 'img_url': 'http://ec1img.pchome.com.tw//items/QAANAIA9007TQ62/000001_1485146861.jpg', 'url': 'http://24h.pchome.com.tw/prod/QAANAI-A9007TQ62'}

Process finished with exit code 0
```

原始碼[點我](https://github.com/yotsuba1022/web-crawler-practice/blob/master/ch7/pchome_crawler.py)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://clu.gitbook.io/python-web-crawler-note/72-pchome-24h-apipa-chong.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
