Like the title says I am working on a little project where I need to "open link, click on a button, replace a part of the link and do the task again"
My code is a little messy and I am still a newbie, but this is it so far, and the problem I am running into is that the page doesn't open when I add the 'if else' function. The page just doesn't open, I could do without the if else, but since the button's xpath changes in random numbered pages that's the only solution I can think of
PATH = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=PATH)
driver.maximize_window()
button = driver.find_element_by_xpath("/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div[2]/div[3]/div/div[2]/button")
button1 = driver.find_element_by_xpath("/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div/div[3]/div/button")
for i in range(1,5):
print(f"https://test.com/page/{i}")
driver.get(f"https://test.com/page/{i}")
if button is not None:
button.click()
else:
button1.click()
CodePudding user response:
Load the page before getting the buttons. Also, make sure the button is loaded with this script:
PATH = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=PATH)
driver.maximize_window()
button_selector = "/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div[2]/div[3]/div/div[2]/button"
button1_selector = "/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div/div[3]/div/button"
for i in range(1, 5):
print(f"https://test.com/page/{i}")
# Load the page
driver.get(f"https://test.com/page/{i}")
# Get the buttons
button = driver.find_element_by_xpath(button_selector) or None
button1 = driver.find_element_by_xpath(button1_selector) or None
time.sleep(1) # Make sure the buttons are loaded
if button is not None:
button.click()
elif button1 is not None:
button1.click()
driver.quit() # Be sure to close the driver