Added product page fetching
This commit is contained in:
0
surugaya_api/__init__.py
Normal file
0
surugaya_api/__init__.py
Normal file
1
surugaya_api/consts.py
Normal file
1
surugaya_api/consts.py
Normal file
@@ -0,0 +1 @@
|
||||
SURU_COOKIE_STRING = "safe_search_option=3; safe_search_expired=2; z_hyoji=0; p_adult=1; p_hyoji=0"
|
75
surugaya_api/product.py
Normal file
75
surugaya_api/product.py
Normal file
@@ -0,0 +1,75 @@
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
import aiohttp
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from surugaya_api.consts import SURU_COOKIE_STRING
|
||||
|
||||
@dataclass
|
||||
class ProductStock:
|
||||
condition: str
|
||||
stock: str
|
||||
price: int
|
||||
on_sale_price: Optional[int]
|
||||
|
||||
@property
|
||||
def is_on_sale(self) -> bool:
|
||||
return self.on_sale_price is not None
|
||||
|
||||
@staticmethod
|
||||
def from_item_price(item_price):
|
||||
data: dict = json.loads(item_price.select_one("input").attrs["data-zaiko"])
|
||||
|
||||
return ProductStock(
|
||||
condition=item_price.select_one("label").attrs["data-label"].strip(),
|
||||
stock=data["zaiko"],
|
||||
price=data["baika"],
|
||||
on_sale_price=data.get("price_sale")
|
||||
)
|
||||
|
||||
@dataclass
|
||||
class Product:
|
||||
id: int
|
||||
name: str
|
||||
main_image_href: str
|
||||
stock: [ProductStock]
|
||||
|
||||
@property
|
||||
def in_stock(self):
|
||||
return not self.stock
|
||||
|
||||
|
||||
async def load_product(product_id, aiohttp_session=None):
|
||||
if not aiohttp_session:
|
||||
_aiohttp_session = aiohttp.ClientSession()
|
||||
else:
|
||||
_aiohttp_session = aiohttp_session
|
||||
|
||||
async with _aiohttp_session.get(
|
||||
url="https://www.suruga-ya.jp/product/detail/" + str(product_id),
|
||||
headers={
|
||||
"Cookie": SURU_COOKIE_STRING,
|
||||
},
|
||||
) as response:
|
||||
page = await response.text()
|
||||
|
||||
page_bs = BeautifulSoup(
|
||||
page, features="html.parser"
|
||||
)
|
||||
|
||||
product = Product(
|
||||
id=int(product_id),
|
||||
name=page_bs.select_one("#item_title").text.strip(),
|
||||
main_image_href=page_bs.select_one(".main-pro-img").attrs["src"],
|
||||
stock=[
|
||||
ProductStock.from_item_price(item_price)
|
||||
for item_price in page_bs.select(".item-price")
|
||||
]
|
||||
)
|
||||
|
||||
if not aiohttp_session:
|
||||
await _aiohttp_session.close()
|
||||
|
||||
return product
|
Reference in New Issue
Block a user