-
Notifications
You must be signed in to change notification settings - Fork 290
/
Copy pathexperimental.py
245 lines (204 loc) · 8.93 KB
/
experimental.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import os
import sys
import six
import pause
import requests
import argparse
import logging.config
from selenium import webdriver
from dateutil import parser as date_parser
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
"""
This is an experimental script which attempts at utilizing some Nike APIs.
Current implementation:
1. Login with Selenium
2. Using the driver's stored cookies, make a Nike API request to add the desired item to your cart
3. Load the checkout page and place an order
Not sure if this will be any faster than the other script...
"""
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {
"format": "%(asctime)s [PID %(process)d] [Thread %(thread)d] [%(levelname)s] [%(name)s] %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "INFO",
"formatter": "default",
"stream": "ext://sys.stdout"
}
},
"root": {
"level": "INFO",
"handlers": [
"console"
]
}
})
NIKE_HOME_URL = "https://www.nike.com/us/en_us/"
NIKE_CHECKOUT_URL = "https://www.nike.com/checkout"
NIKE_CART_API_URL = "https://secure-store.nike.com/us/services/jcartService"
LOGGER = logging.getLogger()
def run(driver, username, password, product_id, sku_id, shoe_size, login_time=None, release_time=None,
page_load_timeout=None, screenshot_path=None, purchase=False, num_retries=None):
driver.maximize_window()
driver.set_page_load_timeout(page_load_timeout)
if login_time:
LOGGER.info("Waiting until login time: " + login_time)
pause.until(date_parser.parse(login_time))
try:
login(driver=driver, username=username, password=password)
except Exception as e:
LOGGER.exception("Failed to login: " + str(e))
six.reraise(Exception, e, sys.exc_info()[2])
if release_time:
LOGGER.info("Waiting until release time: " + release_time)
pause.until(date_parser.parse(release_time))
num_retries_attempted = 0
while True:
try:
try:
LOGGER.info("Adding item to cart")
add_item_to_cart(driver=driver, product_id=product_id, sku_id=sku_id, size=shoe_size)
except Exception as e:
LOGGER.exception("Failed to add item to cart " + str(e))
six.reraise(Exception, e, sys.exc_info()[2])
try:
LOGGER.info("Requesting page: " + NIKE_CHECKOUT_URL)
driver.get(NIKE_CHECKOUT_URL)
except TimeoutException:
LOGGER.info("Page load timed out but continuing anyway")
if purchase:
try:
click_place_order_button(driver=driver)
except Exception as e:
LOGGER.exception("Failed to click place order button: " + str(e))
six.reraise(Exception, e, sys.exc_info()[2])
LOGGER.info("Purchased shoe")
break
except Exception:
if num_retries and num_retries_attempted < num_retries:
num_retries_attempted += 1
continue
else:
break
if screenshot_path:
LOGGER.info("Saving screenshot")
driver.save_screenshot(screenshot_path)
driver.quit()
def login(driver, username, password):
try:
LOGGER.info("Requesting page: " + NIKE_HOME_URL)
driver.get(NIKE_HOME_URL)
except TimeoutException:
LOGGER.info("Page load timed out but continuing anyway")
LOGGER.info("Waiting for login button to become clickable")
wait_until_clickable(driver=driver, xpath="//li[@js-hook='exp-join-login']/button")
LOGGER.info("Clicking login button")
driver.find_element_by_xpath("//li[@js-hook='exp-join-login']/button").click()
LOGGER.info("Waiting for login fields to become visible")
wait_until_visible(driver=driver, xpath="//input[@name='emailAddress']")
LOGGER.info("Entering username and password")
email_input = driver.find_element_by_xpath("//input[@name='emailAddress']")
email_input.clear()
email_input.send_keys(username)
password_input = driver.find_element_by_xpath("//input[@name='password']")
password_input.clear()
password_input.send_keys(password)
LOGGER.info("Logging in")
driver.find_element_by_xpath("//input[@value='LOG IN']").click()
wait_until_visible(driver=driver, xpath="//span[text()='My Account']")
LOGGER.info("Successfully logged in")
def click_place_order_button(driver):
xpath = "//button[text()='Place Order']"
LOGGER.info("Waiting for place order button to become clickable")
wait_until_clickable(driver, xpath=xpath, duration=10)
LOGGER.info("Clicking place order button")
driver.find_element_by_xpath(xpath).click()
def add_item_to_cart(driver, product_id, sku_id, size):
cookies = driver.get_cookies()
params = {
"action": "addItem",
"lang_locale": "en_US",
"catalogId": "1",
"productId": product_id,
"qty": "1",
"price": "",
"skuAndSize": "{}:{}".format(sku_id, size),
"rt": "json",
"view": "3",
"skuId": sku_id,
"displaySize": "10"
}
headers = {
"user-agent": "Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
"origin": "https://www.nike.com",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9",
"accept": "*/*",
"scheme": "https"
}
response = requests.get(url=NIKE_CART_API_URL,
params=params, headers=headers, cookies=cookies)
if response.status_code != 200:
raise Exception("Request to add item to cart failed (code {}): {}".format(
response.status_code, response.text))
def wait_until_clickable(driver, xpath=None, class_name=None, duration=10000, frequency=0.01):
if xpath:
WebDriverWait(driver, duration, frequency).until(EC.element_to_be_clickable((By.XPATH, xpath)))
elif class_name:
WebDriverWait(driver, duration, frequency).until(EC.element_to_be_clickable((By.CLASS_NAME, class_name)))
def wait_until_visible(driver, xpath=None, class_name=None, duration=10000, frequency=0.01):
if xpath:
WebDriverWait(driver, duration, frequency).until(EC.visibility_of_element_located((By.XPATH, xpath)))
elif class_name:
WebDriverWait(driver, duration, frequency).until(EC.visibility_of_element_located((By.CLASS_NAME, class_name)))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--username", required=True)
parser.add_argument("--password", required=True)
parser.add_argument("--product-id", required=True)
parser.add_argument("--sku-id", required=True)
parser.add_argument("--shoe-size", required=True)
parser.add_argument("--login-time", default=None)
parser.add_argument("--release-time", default=None)
parser.add_argument("--screenshot-path", default=None)
parser.add_argument("--page-load-timeout", type=int, default=2)
parser.add_argument("--driver-type", default="firefox", choices=("firefox", "chrome"))
parser.add_argument("--headless", action="store_true")
parser.add_argument("--purchase", action="store_true")
parser.add_argument("--num-retries", type=int, default=1)
args = parser.parse_args()
driver = None
if args.driver_type == "firefox":
options = webdriver.FirefoxOptions()
if args.headless:
options.add_argument("--headless")
executable_path = None
if sys.platform == "darwin":
executable_path = "./bin/geckodriver_mac"
elif "linux" in sys.platform:
executable_path = "./bin/geckodriver_linux"
driver = webdriver.Firefox(executable_path=executable_path, firefox_options=options, log_path=os.devnull)
elif args.driver_type == "chrome":
options = webdriver.ChromeOptions()
if args.headless:
options.add_argument("headless")
executable_path = None
if sys.platform == "darwin":
executable_path = "./bin/chromedriver_mac"
elif "linux" in sys.platform:
executable_path = "./bin/chromedriver_linux"
driver = webdriver.Chrome(executable_path=executable_path, chrome_options=options)
run(driver=driver, username=args.username, password=args.password, product_id=args.product_id,
sku_id=args.sku_id, shoe_size=args.shoe_size, login_time=args.login_time, release_time=args.release_time,
page_load_timeout=args.page_load_timeout, screenshot_path=args.screenshot_path,
purchase=args.purchase, num_retries=args.num_retries)