Fix Teespring API

master
Nikola Forró 5 years ago
parent cea53a2a06
commit 67a1186cfb

@ -1,32 +1,31 @@
import json import json
import re
from urllib.parse import urlparse, parse_qs from urllib.parse import urlparse, parse_qs
from pyquery import PyQuery as pq
from requests_futures.sessions import FuturesSession from requests_futures.sessions import FuturesSession
BASE_URL = 'https://teespring.com' BASE_URL = 'https://teespring.com'
CAMPAIGN_DATA = re.compile(r'var campaign_data = (\{.*\})</script>')
class Teespring(object): class Teespring(object):
def __init__(self, store_name): def __init__(self, store_name):
self.store_name = store_name self.store_name = store_name
def _parse_variants(self, pid, html): def _parse_variants(self, pid, campaign_data):
result = [] result = []
d = pq(html) product = campaign_data['products'][pid]
for div in d('div.image_stack__container[data-product-id="{0}"]'.format(pid)).items(): for color in product['colors']:
color_id = div.attr('data-color-id') cid = str(color['id'])
front_url = div.find('div[data-side="front"]').find('img').eq(0).attr('data-original') front = [i for i in product['images'][cid] if i['side'] == 'front']
back_url = div.find('div[data-side="back"]').find('img').eq(0).attr('data-original') back = [i for i in product['images'][cid] if i['side'] == 'back']
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]
result.append(dict( result.append(dict(
color_id=color_id, color_id=cid,
front_url=front_url, front_url=front[0]['src'],
back_url=back_url, back_url=back[0]['src'],
color_value=color_value)) color_value=color['value']))
return result return result
def fetch_products(self): def fetch_products(self):
@ -54,8 +53,11 @@ class Teespring(object):
q = parse_qs(urlparse(next_url).query) q = parse_qs(urlparse(next_url).query)
page = q.get('page', [])[0] page = q.get('page', [])[0]
for product, request in zip(result, requests): 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] pid = q.get('pid', [])[0]
r = request.result() 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 return result

Loading…
Cancel
Save