-
Notifications
You must be signed in to change notification settings - Fork 0
/
share.py
866 lines (677 loc) · 31.5 KB
/
share.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
import argparse
import logging
import numpy as np
import os
import pyautogui
import random
import sys
import textwrap
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options as ChromeOptions
# TODO: Handle safari driver manager
from selenium.webdriver.safari.webdriver import WebDriver as SafariDriver
from selenium.webdriver.safari.options import Options as SafariOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.edge.options import Options as EdgeOptions
# Configure the logger
logging.basicConfig(
filename='share.log', # Specify the log file name
level=logging.DEBUG, # Set the logging level to DEBUG or higher
format='[%(levelname)s] %(asctime)s - %(message)s' # Specify the log message format
)
logger = logging.getLogger(__name__)
# Constants for web drivers
DRIVER_CHROME = 'chrome'
DRIVER_SAFARI = 'safari'
DRIVER_FIREFOX = 'firefox'
DRIVER_EDGE = 'edge'
# # Mapping dictionary for drivers
DRIVER_OPTIONS = {
DRIVER_CHROME: webdriver.Chrome,
DRIVER_SAFARI: webdriver.Safari,
DRIVER_FIREFOX: webdriver.Firefox,
DRIVER_EDGE: webdriver.Edge,
}
# Function to set up the driver
def setup_driver(driver_name):
try:
# Convert the driver_name to lowercase for consistent comparison
driver_name = driver_name.lower()
# Check if the provided driver_name is supported
if driver_name in DRIVER_OPTIONS:
# Check the specific driver_name to create the appropriate driver instance
if driver_name == DRIVER_CHROME:
# Create an instance of ChromeOptions
chrome_options = ChromeOptions()
# Create a Chrome driver instance with ChromeDriverManager and pass chrome_options as an argument
driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)
driver.implicitly_wait(10)
return driver
# TODO: EXTEND SAFARI FUNCTIONALITIES
elif driver_name == DRIVER_SAFARI:
# Create an instance of SafariOptions
safari_options = SafariOptions()
# Create a Safari driver instance with SafariDriver and pass safari_options as an argument
driver = webdriver.Safari(SafariDriver().install(), options = safari_options)
driver.implicitly_wait(10)
return driver
elif driver_name == DRIVER_FIREFOX:
# Create an instance of FirefoxOptions
firefox_options = FirefoxOptions()
# Create a Firefox driver instance with GeckoDriverManager and pass firefox_options as an argument
driver = webdriver.Firefox(options = firefox_options)
driver.implicitly_wait(10)
return driver
elif driver_name == DRIVER_EDGE:
# Create an instance of EdgeOptions
edge_options = EdgeOptions()
# Create an Edge driver instance with EdgeChromiumDriverManager and pass edge_options as an argument
driver = webdriver.Edge(EdgeChromiumDriverManager().install(), options = edge_options)
driver.implicitly_wait(10)
return driver
else:
# Print an error message to the console and log the error
print(textwrap.dedent('''
[*] ERROR Driver argument value not supported!
Check the help (-h) argument for supported values.
'''))
logger.info(textwrap.dedent('''
[*] ERROR Driver argument value not supported!
Check the help (-h) argument for supported values.
'''))
except ValueError as v:
# Log and display error messages if a ValueError occurs
logger.error("Error occurred during driver setup: %s", v)
print("[*] ERROR Driver argument value not supported! Check the help (-h) argument for supported values.")
logger.info("[*] ERROR Driver argument value not supported! Check the help (-h) argument for supported values.")
sys.exit(-1)
except NameError as n:
# Log and display error messages if a NameError occurs
logger.error("Error occurred during driver setup: %s", n)
print(textwrap.dedent('''
[*] ERROR You don't have the web driver for argument
given ({}) you need to download it, go here for
installation info:
https://selenium-python.readthedocs.io/installation.html#drivers
'''.format(driver)))
logger.info(textwrap.dedent('''
[*] ERROR You don't have the web driver for argument
given ({}) you need to download it, go here for
installation info:
https://selenium-python.readthedocs.io/installation.html#drivers
'''.format(driver)))
sys.exit(-2)
except Exception as e:
# Log and display error messages
logger.error("Error occurred while initializing the driver: %s", e)
print(textwrap.dedent('''
[*] ERROR the selected driver may not be setup correctly.
Ensure you can access it from the command line and
try again.
{}
'''.format(e)))
logger.info(textwrap.dedent('''
[*] ERROR the selected driver may not be setup correctly.
Ensure you can access it from the command line and
try again.
{}
'''.format(e)))
sys.exit(-3)
else:
pass
# Add the handle_captcha function
def handle_captcha():
# Print informative messages about CAPTCHA challenge
print("[*] ERROR in Share : Thwarted by Captchas")
print("[*] Please open the browser to the Poshmark login page.")
print("[*] Solve the CAPTCHA and log in as a human.")
print("[*] Once you've successfully logged in, come back here.")
print("[*] Press Enter to continue the script after solving the CAPTCHA.")
# Log informative messages about CAPTCHA challenge
logger.info("[*] ERROR in Share : Thwarted by Captchas")
logger.info("[*] Please open the browser to the Poshmark login page.")
logger.info("[*] Solve the CAPTCHA and log in as a human.")
logger.info("[*] Once you've successfully logged in, come back here.")
logger.info("[*] Press Enter to continue the script after solving the CAPTCHA.")
# Wait for the user to press Enter to continue
input("[*] If you want to quit, enter 'q' and press Enter.")
# Check if the user wants to quit the script
quit_choice = input().lower().strip()
if quit_choice == 'q':
# Print and log that the user chose to exit the script and exit
print("[*] Exiting the script.")
logger.info("[*] Exiting the script.")
sys.exit(-4)
# Add the check_quit_input function
def check_quit_input():
# Define the quit message for user input
quit_mes = textwrap.dedent('''
[*] if you would like to quit, enter [q]
otherwise, enter any other key to continue
''')
# Prompt the user with the quit message and store their input
quit_selection = input(quit_mes)
qs = str(quit_selection).lower() # Convert input to lowercase
# Check if the user's input is 'q' (quit)
if qs == 'q':
global quit_input # Access the global quit_input variable
quit_input = True # Set the global variable to True (indicating user wants to quit)
else:
pass # If user doesn't want to quit, continue with the script
# Modify the login function
def login(debugger = False):
# Set the maximum number of retries
max_retries = 5
retries = 0
# If debugger flag is True, enable Python debugger (pdb)
if debugger is True:
import pdb; pdb.set_trace()
else:
pass # Otherwise, continue without debugger
# URL of the Poshmark login page
url = "https://poshmark.com/login"
driver.get(url) # Open the URL in the driver's browser
time.sleep(get_random_delay(5)) # Wait for a random delay before proceeding
# Attempt login with retry mechanism
while retries < max_retries:
try:
## Perform login
print(textwrap.dedent('''
[*] Logging into Poshmark seller account "{}" ...
The share war will begin momentarily...
'''.format(poshmark_username)))
logger.info(textwrap.dedent('''
[*] Logging into Poshmark seller account "{}" ...
The share war will begin momentarily...
'''.format(poshmark_username)))
username = driver.find_element(By.NAME, "login_form[username_email]")
username.send_keys(poshmark_username)
time.sleep(get_random_delay(5))
password = driver.find_element(By.NAME, "login_form[password]")
password.send_keys(poshmark_password)
time.sleep(get_random_delay(5))
password.send_keys(Keys.RETURN)
time.sleep(get_random_delay(5))
## Check for Captcha
try:
captcha_pat = "//span[@class='base_error_message']"
captcha_fail = driver.find_element(By.XPATH, "captcha_pat")
## If Captcha is detected
if len(str(captcha_fail)) > 100:
print("Captcha detected. Manual intervention required.")
logger.info("Captcha detected. Manual intervention required.")
handle_captcha() # Call the handle_captcha function
retries += 1 # Increment the retries counter
# Retry login after manual intervention
if login(debugger = True):
return
continue
except NoSuchElementException:
pass
# Login successful, break out of the loop
break
except Exception as e:
# Handle Captcha Challenge
print(textwrap.dedent('''
[*] ERROR in Share Bot: Thwarted by Captchas
you may now attempt to login with the python debugger
'''))
logger.info(textwrap.dedent('''
[*] ERROR in Share Bot: Thwarted by Captchas
you may now attempt to login with the python debugger
'''))
logger.error("Error occurred during login: %s", e)
check_quit_input()
if quit_input:
break
retries += 1 # Increment the retries counter
time.sleep(get_random_delay(30)) # Wait for a few seconds before retrying
else:
# The loop completed without successful login, handle the situation accordingly
logger.info("Login failed after multiple attempts. Exiting the script.")
sys.exit(-5)
# Continue with the rest of the login process
time.sleep(get_random_delay(10))
seller_page = get_seller_page_url(args.account)
driver.get(seller_page)
## Confirm account to share if not username
if (args.bypass == True):
pass
else:
if (args.account != poshmark_username):
confirm_account_sharing(args.account, poshmark_username)
if (quit_input is True):
return False
else:
pass
else:
pass
return True
# Define the deploy_share_bot function
def deploy_share_bot(driver, n = 3, order = True, random_subset = 0):
# Log and print the initiation of the share bot
logger.info("[*] DEPLOYING SHARE BOT")
print("[*] DEPLOYING SHARE BOT")
try:
# Attempt to perform the following steps within a try block
if login():
pass # If login is successful, continue; otherwise, return
else:
return # If login is not successful, exit the function
# Scroll the page to load more items
scroll_page(n)
## Share Icons and Order
# Get the icons of items available for sharing
share_icons = get_closet_share_icons()
if order is True:
share_icons.reverse() # Reverse the order of sharing icons if specified
else:
pass
## Share Random Subset of Items
if random_subset != 0:
try:
random_subset = int(random_subset)
# Log and print information about sharing a random subset of items
logger.info(textwrap.dedent('''
[*] you have selected to share a random subset of {} items
from all {} PoshMark listings in the closet...
please wait...
'''.format(random_subset, len(share_icons))))
print(textwrap.dedent('''
[*] you have selected to share a random subset of {} items
from all {} PoshMark listings in the closet...
please wait...
'''.format(random_subset, len(share_icons))))
# Randomly select a subset of items to share
share_icons = np.random.choice(share_icons, random_subset, replace=False).tolist()
except Exception as e:
print("Error occurred while selecting random subset: %s", e)
logger.warning("Error occurred while selecting random subset: %s", e)
pass # If there's an error, log a warning and continue
else:
pass
## Share Message
# Log and print the sharing message with the number of items to be shared
logger.info(textwrap.dedent('''
[*] sharing PoshMark listings for {} items in closet...
please wait...
'''.format(len(share_icons))))
print(textwrap.dedent('''
[*] sharing PoshMark listings for {} items in closet...
please wait...
'''.format(len(share_icons))))
## Share Listings
# Iterate through each item and share it with followers
for item in share_icons:
clicks_share_followers(item)
# Access and log the captured requests using selenium-wire
for request in driver.requests:
if request.response:
print(request.url)
logger.info(request.url)
print(request.method)
logger.info(request.method)
print(request.reponse.status_code)
logger.info(request.response.status_code)
print(request.response.headers)
logger.info(request.response.headers)
# Log and print successful sharing completion message
logger.info("[*] closet successfully shared...posh-on...")
print("[*] closet successfully shared...posh-on...")
pass
except Exception as e:
# Catch and log and print any exceptions that occurred during the share bot deployment
logger.info("[*] ERROR in Share Bot")
print("[*] ERROR in Share Bot")
logger.error("Error occurred during share war deployment: %s", e)
print("Error occurred during share war deployment: %s", e)
pass # Continue the script even if an error occurred
## Closing Message
# Calculate loop delay in minutes and format the current time
loop_delay = int(random_loop_time/60)
current_time = time.strftime("%I:%M%p on %b %d, %Y")
# Log and print the delay and current time before the next iteration
logger.info(textwrap.dedent('''
[*] the share war will continue in {} minutes...
current time: {}
'''.format(loop_delay, current_time)))
print(textwrap.dedent('''
[*] the share war will continue in {} minutes...
current time: {}
'''.format(loop_delay, current_time)))
# Add the simulate_human_interaction function
def simulate_human_interaction():
try:
# Simulate mouse movement to create a human-like interaction pattern
x, y = pyautogui.position()
# Move the mouse cursor slightly to different positions
pyautogui.moveTo(x + 10, y + 10, duration=0.5)
pyautogui.moveTo(x - 10, y - 10, duration=0.5)
pyautogui.moveTo(x, y, duration=0.5)
# Scroll up and down to mimic human scrolling behavior
pyautogui.scroll(3)
# Pause for a random delay before further interaction
time.sleep(get_random_delay_for_interaction(2))
pyautogui.scroll(-3) # Scroll back up
except Exception as e:
# Catch and log any exceptions that occurred during simulating interaction
logger.warning("Error occurred during simulating human interaction: %s", e)
print("Error occurred during simulating human interaction: %s", e)
pass # Continue the script even if an error occurred
# Define the get_random_delay function
def get_random_delay(mean_delay):
# Generate a list of random times, adding two random values and the mean delay
times = np.random.rand(1000) + np.random.rand(1000) + mean_delay
# Choose and return a random time from the generated list
return np.random.choice(times, 1).tolist()[0]
# Define the get_random_delay_for_interaction function
def get_random_delay_for_interaction(mean_delay):
# Call the get_random_delay function to get a random delay
return get_random_delay(mean_delay)
# Define the confirm_account_sharing function
def confirm_account_sharing(account, username):
try:
# Get user input for confirming account sharing request
logger.info(textwrap.dedent('''
[*] You have requested to share
the items in another Poshmark closet:
------------------------------------
[*]: {}
------------------------------------
'''.format(account)))
print(textwrap.dedent('''
[*] You have requested to share
the items in another Poshmark closet:
------------------------------------
[*]: {}
------------------------------------
'''.format(account)))
confirm_mes = (textwrap.dedent('''
[*] To confirm this request, enter [y].
To cancel and share your closet items instead, enter [n]:
'''))
confirm_selection = input(confirm_mes)
cs = str(confirm_selection).lower()
if cs == 'y':
pass # Proceed with account sharing
elif cs == 'n':
# Redirect to the user's own closet page
seller_page = get_seller_page_url(username)
driver.get(seller_page)
else:
# Handle invalid selection from the user
logger.info('[*] You have entered an invalid selection...')
print('[*] You have entered an invalid selection...')
check_quit_input() # Check if the user wants to quit
if quit_input is True:
pass
else:
confirm_account_sharing(account, username) # Recurse to reconfirm
except Exception as e:
# Catch and log any exceptions that occurred during account sharing confirmation
logger.warning("Error occurred during account sharing confirmation: %s", e)
print("Error occurred during account sharing confirmation: %s", e)
pass # Continue the script even if an error occurred
# Define the get_seller_page_url function
def get_seller_page_url(poshmark_account):
# Generate the URL for the seller's Poshmark closet page
url_stem = 'https://poshmark.com/closet/'
available = '?availability=available'
url = '{}{}{}'.format(url_stem, poshmark_account, available)
return url
# Define the scroll_page function
def scroll_page(n, delay = 3):
try:
scroll = 0
screen_heights = [0]
logger.info("[*] Scrolling through all items in closet...")
print("[*] Scrolling through all items in closet...")
for i in range(1, n + 1):
scroll += 1
scroll_script = "window.scrollTo(0, document.body.scrollHeight);"
driver.execute_script(scroll_script)
height = driver.execute_script("return document.documentElement.scrollHeight")
last_height = screen_heights[-1:][0]
if height == last_height:
return # Reached the end of the page, exit
else:
screen_heights.append(height)
time.sleep(get_random_delay(delay)) # Pause with random delay
except Exception as e:
# Catch and log any exceptions that occurred during page scrolling
logger.warning("Error occurred during page scrolling: %s", e)
print("Error occurred during page scrolling: %s", e)
pass # Continue the script even if an error occurred
# Define the get_closet_urls function
def get_closet_urls():
# Find all items' details elements and extract their URLs
items = driver.find_elements(By.XPATH, "//div[@class='item-details']")
urls = [i.find_element(By.CSS_SELECTOR, "a").get_attribute('href') for i in items]
return urls
# Define the get_closet_share_icons function
def get_closet_share_icons():
try:
item_pat = "//div[@class='social-info social-actions d-fl ai-c jc-c']"
# Find all share icons within the closet items and return them
items = driver.find_elements(By.XPATH, "item_pat")
share_icons = [i.find_element(By.CSS_SELECTOR, "a[class='share']") for i in items]
return share_icons
except Exception as e:
# Handle any exceptions that occurred during retrieving share icons
logger.error("Error occurred while getting closet share icons: %s", e)
print("Error occurred while getting closet share icons: %s", e)
return []
# Define the clicks_share_followers function
def clicks_share_followers(share_icon, d=4.5):
try:
## First share click
driver.execute_script("arguments[0].click();", share_icon);
time.sleep(get_random_delay(d))
## Second share click
share_pat = "//a[@class='pm-followers-share-link grey']"
share_followers = driver.find_element(By.XPATH, "share_pat")
driver.execute_script("arguments[0].click();", share_followers);
time.sleep(get_random_delay(d))
except Exception as e:
# Handle any exceptions that occurred during clicking share icons
logger.error("Error occurred while clicking share icons: %s", e)
print("Error occurred while clicking share icons: %s", e)
pass
# Define the open_closet_item_url function
def open_closet_item_url(url):
logger.info(url)
print(url)
# Open the provided URL and wait for a random delay
driver.get(url)
time.sleep(get_random_delay(5))
if __name__ == "__main__":
##################################
## Arguments for Script
##################################
## Create a custom argument formatter that supports raw text and default values
class RawTextArgumentDefaultsHelpFormatter(
argparse.ArgumentDefaultsHelpFormatter,
argparse.RawTextHelpFormatter
):
pass
# Check if the 'credentials.py' file exists
exists = os.path.isfile('./credentials.py')
if not exists:
# Inform the user if 'credentials.py' does not exist and provide instructions
logger.info(textwrap.dedent('''
[*] ERROR: `credentials.py` file does not exist.
You may need to create the file, for example,
by copying `example_credentials.py`...
[*] In terminal, enter the following command:
cp example_credentials.py credentials.py
[*] Then edit credentials.py with your
poshmark closet and password.
'''))
print(textwrap.dedent('''
[*] ERROR: `credentials.py` file does not exist.
You may need to create the file, for example,
by copying `example_credentials.py`...
[*] In terminal, enter the following command:
cp example_credentials.py credentials.py
[*] Then edit credentials.py with your
poshmark closet and password.
'''))
sys.exit(-6)
else:
import credentials
## Fail gracefully if the username or password not specified in credentials.py
try:
poshmark_username = credentials.poshmark_username
poshmark_password = credentials.poshmark_password
except AttributeError:
# Inform the user if username and/or password is missing and provide instructions
logger.info(textwrap.dedent('''
[*] ERROR: Username and/or password not specified...
[*] You may need to uncomment poshmark_username and
poshmark_password in credentials.py
'''))
print(textwrap.dedent('''
[*] ERROR: Username and/or password not specified...
[*] You may need to uncomment poshmark_username and
poshmark_password in credentials.py
'''))
sys.exit(-7)
## Verify that the user is using their Poshmark username and not email
if '@' in poshmark_username:
# Inform the user to use Poshmark username for login
logger.info(textwrap.dedent('''
[*] Do not use your email address to log in...
use your Poshmark username (closet) instead...
'''))
print(textwrap.dedent('''
[*] Do not use your email address to log in...
use your Poshmark username (closet) instead...
'''))
sys.exit(-8)
# Define the argument parser with description and custom formatter
parser = argparse.ArgumentParser(
description=textwrap.dedent('''
[*] Help file for share.py
from the poshmark_sharing repository:
https://github.com/lyndskg/posh-a-matic
'''),
usage = 'use "python3 %(prog)s --help" or "python3 share.py -h" for more information',
formatter_class=RawTextArgumentDefaultsHelpFormatter)
# Add command line arguments for different options
parser.add_argument("-t", "--time", default=14400, type=float,
help=textwrap.dedent('''\
loop time in seconds to repeat the code
:: example, repeat every two hours:
-t 7200
'''))
parser.add_argument("-n", "--number", default=1000, type=int,
help="number of closet scrolls")
parser.add_argument("-o", "--order", default=True, type=bool,
help="preserve closet order")
parser.add_argument("-r", "--random_subset", default=0, type=int,
help="select a random subset (number) of items to share")
parser.add_argument("-a", "--account", default=poshmark_username,
type=str,help=textwrap.dedent('''\
the poshmark closet account you want to share
(default is the login account in credentials.py)
:: example, share another user's closet items:
-a another_username
'''))
parser.add_argument("-b", "--bypass", default=False, type=bool,
help=textwrap.dedent('''\
option to bypass user confirmation
by default, if the account to be shared is not equal
to the poshmark username, the user will be prompted to
confirm this selection
:: example, bypass user confirmation
-b True
'''))
parser.add_argument("-d", "--driver", default='0', type=str,
help=textwrap.dedent('''\
selenium web driver selection
drivers may be called by either entering the name
of the driver or entering the numeric code
for that driver name as follows:
Chrome == 0, Safari == 1, Firefox == 2, Edge == 3
:: example, use Firefox:
-d Firefox
-d 2
:: example, use Chrome:
-d Chrome
-d 0
'''))
# Parse the command line arguments
args = parser.parse_args()
# Handle case when account is not provided, use the one from credentials.py
if args.account is None:
args.account = credentials.poshmark_username
##################################
## Run Script
##################################
## Try to start driver
global driver
driver = setup_driver(args.driver) # Capture the returned driver
## Run Main App
## Start Share War Loop
starttime = time.time()
max_retries = 5 # Set the maximum number of retries
global quit_input
quit_input = False
while quit_input is False:
try:
## Time Delay: While Loop
random_loop_time = get_random_delay(args.time)
quit_input = False
deploy_share_bot(driver, args.number, args.order, args.random_subset)
if quit_input:
break
time.sleep(get_random_delay(10))
driver.close()
time.sleep(get_random_delay(random_loop_time - ((time.time() - starttime) % random_loop_time)))
except NoSuchElementException as e:
# Handle NoSuchElementException
logger.error("Element not found: %s", e)
print("Element not found: %s", e)
check_quit_input()
if quit_input:
driver.quit()
sys.exit(-9)
else:
pass
except Exception as e:
# Handle other exceptions
logger.error("ERROR: %s", e)
print("ERROR: %s", e)
check_quit_input()
if quit_input:
pass
else:
# Sleep for some time before retrying
time.sleep(get_random_delay(30))
# Retry loop
retries = 0
while retries < max_retries:
try:
# Continue with the next iteration of the main loop
break
except Exception as e:
# Retry again
logger.error("ERROR (Retry %d): %s", retries + 1, e)
print("ERROR (Retry %d): %s", retries + 1, e)
time.sleep(get_random_delay(30))
else:
# The loop completed without success, handle the situation accordingly
logger.error("Exceeded maximum retries. Exiting the script.")
print("Exceeded maximum retries. Exiting the script.")
sys.exit(-10)
driver.quit()
sys.exit()