I'm pretty much brand new to coding in Python, this is my first python code I've written. I'm coding a bot that will click a a web element via the xpath, I'm trying to make it go back to the original web page if the element is not there or if a different element is present Here's a segment of the code
# Wait for the second web element to be clickable
followbutton = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div/div[2]/div/header[1]/div/div[1]/aside[2]/div/div/div[1]/div[1]/div[2]/button"))
)
followbutton.click()
However, sometimes the follow button has a slightly different xpath, and instead the Xpath is
/html/body/div[3]/div/div[2]/div/header[1]/div/div[1]/aside[2]/div/div/div[1]/div[1]/div[2]/div/button
instead of
"/html/body/div[3]/div/div[2]/div/header[1]/div/div[1]/aside[2]/div/div/div[1]/div[1]/div[2]/button"
How can I implement an if then statement so that if the xpath is this one:
/html/body/div[3]/div/div[2]/div/header[1]/div/div[1]/aside[2]/div/div/div[1]/div[1]/div[2]/div/button
then it does driver.back()
but if it's this one: /html/body/div[3]/div/div[2]/div/header[1]/div/div[1]/aside[2]/div/div/div[1]/div[1]/div[2]/button
then it does followbutton.click()?
I'm looking for any suggestions, Here's what the full segment of code looks like
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
import time
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# Set the starting page number
page_num = 32
while True:
# Navigate to the URL with the current page number
url = f"https://urlhere.com/page={page_num}"
driver.get(url)
time.sleep(20)
try:
# Wait for the first web element to be clickable
user1 = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div/div[2]/div/main/div/div[1]/div/div"))
)
user1.click()
# Wait for 10 seconds
time.sleep(10)
# Wait for the second web element to be clickable
followbutton = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div/div[2]/div/header[1]/div/div[1]/aside[2]/div/div/div[1]/div[1]/div[2]/button"))
)
followbutton.click()
time.sleep(3)
driver.back()
# Wait for 5 seconds
time.sleep(5)
# 2nd user
user2 = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div/div[2]/div/main/div/div[2]/div/div"))
)
user2.click()
time.sleep(2)
# 2nd users follow button
followbutton2 = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/div[3]/div/div[2]/div/header[1]/div/div[1]/aside[2]/div/div/div[1]/div[1]/div[2]/button"))
)
followbutton2.click()
driver.back()
except:
# If any exception occurs, break out of the loop
break
# Increment the page number
page_num += 1
# Close the browser window
driver.quit()