From 67a1186cfb94b798618ec90350fcd76f929ed0ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Forr=C3=B3?= Date: Sat, 10 Aug 2019 18:58:14 +0200 Subject: [PATCH] Fix Teespring API --- teespring-api/teespring.py | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/teespring-api/teespring.py b/teespring-api/teespring.py index c4c78d2..128ec13 100644 --- a/teespring-api/teespring.py +++ b/teespring-api/teespring.py @@ -1,32 +1,31 @@ import json +import re from urllib.parse import urlparse, parse_qs -from pyquery import PyQuery as pq from requests_futures.sessions import FuturesSession BASE_URL = 'https://teespring.com' +CAMPAIGN_DATA = re.compile(r'var campaign_data = (\{.*\})') class Teespring(object): def __init__(self, store_name): self.store_name = store_name - def _parse_variants(self, pid, html): + def _parse_variants(self, pid, campaign_data): result = [] - d = pq(html) - for div in d('div.image_stack__container[data-product-id="{0}"]'.format(pid)).items(): - color_id = div.attr('data-color-id') - front_url = div.find('div[data-side="front"]').find('img').eq(0).attr('data-original') - back_url = div.find('div[data-side="back"]').find('img').eq(0).attr('data-original') - li = d('li.product__color_list_item[data-product-id="{0}"][data-color-id="{1}"]'.format(pid, color_id)).eq(0) - color_value = li.find('div').eq(0).attr('style').split(':')[1] + product = campaign_data['products'][pid] + for color in product['colors']: + cid = str(color['id']) + front = [i for i in product['images'][cid] if i['side'] == 'front'] + back = [i for i in product['images'][cid] if i['side'] == 'back'] result.append(dict( - color_id=color_id, - front_url=front_url, - back_url=back_url, - color_value=color_value)) + color_id=cid, + front_url=front[0]['src'], + back_url=back[0]['src'], + color_value=color['value'])) return result def fetch_products(self): @@ -54,8 +53,11 @@ class Teespring(object): q = parse_qs(urlparse(next_url).query) page = q.get('page', [])[0] for product, request in zip(result, requests): - q = parse_qs(urlparse(product['url']).fragment) + q = parse_qs(urlparse(product['url']).query) pid = q.get('pid', [])[0] r = request.result() - product['variants'] = self._parse_variants(pid, r.text) + m = CAMPAIGN_DATA.search(r.text) + if m: + campaign_data = json.loads(m.group(1)) + product['variants'] = self._parse_variants(pid, campaign_data) return result