-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddItemToCart.py
91 lines (69 loc) · 2.47 KB
/
AddItemToCart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import requests
import scrapy
import json
import webbrowser
import os
import sys
session = requests.session()
print("Enter Product Url")
product_url = input()
#product_url = "https://www.shoppersstop.com/p-204128165_9407/colorChange?colorCode=204128165_9407" #sample URL
csrf_url = "https://www.shoppersstop.com/getCSRFToken"
add_url = "https://www.shoppersstop.com/cart/add"
csrf_payload = ""
#Product Page
response = session.request("GET", product_url, data=csrf_payload)
#Extracting Product id and Size id
res = scrapy.Selector(text = response.text)
li = res.xpath(".//ul[@class='variant_size_ulClass']/li")
#Extract Product ID
pro = li.xpath(".//input[@class='variantSizeUrl']/@value").extract()[0]
productCode = pro.replace("/p-", "")
#Extract Size ID
sizeCodes = li.xpath(".//input[@id='variantSizeCode']/@value").extract()
buttons = li.xpath(".//button")
#Extract All Sizes
buttonValues = li.xpath(".//button/text()").extract()
#details[] contains all available Size and it's Size Code
details = []
#removing unavailable options
for i in range(len(sizeCodes)):
item = []
if not (buttons[i].xpath("./@disabled")):
item.append(sizeCodes[i])
item.append(buttonValues[i])
details.append(item)
if not details:
print("Out of Stock")
sys.exit()
print ("Available Options")
i = 1
for item in details:
print (str(i) + ". ", end=" ")
print (item[1])
i = i + 1
print ("Select the Size")
user_input = int(input())
itemCode = details[user_input - 1][0]
#Select Size Call
item_select_url = "https://www.shoppersstop.com/p-" + productCode + "/sizeChange"
querystring = {"sizeCode":itemCode,"pincode":""}
response_p = session.request("GET", item_select_url, data=csrf_payload, params=querystring)
#CSRF Call
response = session.request("GET", csrf_url, data=csrf_payload)
_csrf = response.text.strip().replace('"', '')
payload = "qty=1&baseProductCode=" + productCode + "&productCodePost=" + itemCode + "&CSRFToken=" + _csrf + "&undefined="
#add to cart Call
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response_a = session.request("POST", add_url, data=payload, headers=headers)
#Cart Page
cart_url = "https://www.shoppersstop.com/cart"
headers = {'cache-control': "no-cache"}
response_c = session.request("GET", cart_url, data=csrf_payload)
#output cart.html
with open("cart.html", 'wb') as fd:
for chunk in response_c.iter_content(chunk_size=128):
fd.write(chunk)
print ("Item got added to Cart.")
#Open in Browser
webbrowser.open('file://' + os.path.realpath("cart.html"))