Finding Element Within Flexbox With Selenium

Question:

This is similar to a previously asked question, however all solutions that I have found do not work in my unique scenario with this particular website.

I am attempting to click a single top listing by navigating to the page with selenium, however I am unable to find the listings with selenium because they are nested in a series of flexboxes that contain unique IDs and class names. Unfortunately, it seems that the only way I can consistently access the listings for all urls would be to use the xpath, but it is unreachable due to the nested flexboxes.

Here is a snippet of the html of the page, with the item I would like to find and click:

stubhub

Here is my code that is unable to find the element by using the XPATH – I tried using class and CSS selector as well, but was unable to find it.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import espected_conditions as EC
-
url = "https://www.stubhub.com/philadelphia-eagles-philadelphia-tickets-1-21-2023/event/151223773/?quantity=2&sections=195411%2C195410%2C195414%2C195413%2C195409%2C195408%2C195412%2C195415%2C195430%2C195427%2C195432%2C195433%2C195431%2C195428%2C195434%2C195429&ticketClasses=594&listingQty=&multi=true"
-
opt = Options()
opt.headless = False
driver = webdriver.Chrome('chromedriver.exe', options=opt)
driver.maximize_window()
driver.get(url)
wait = WebDriverWait(driver, 10)
-
wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="app"]/div[2]/div/div[2]/div[1]/div/div[2]/div/div/div[1]/div/div/div/div[2]/button')))
driver.find_element(By.XPATH, '//*[@id="app"]/div[2]/div/div[2]/div[1]/div/div[2]/div/div/div[1]/div/div/div/div[2]/button').click()

This code is opening the browser fine as usual, but throwing a timeout exception once the wait for the element to be clickable times out from not finding the element.

Asked By: johne518

||

Answers:

In this case if you want to click the first "Select" button, it is better to use a xpath based on the type of the webelement (button) and on the text contained in the button (Select)

xpath = "//button[text()='Select']"
wait.until(EC.element_to_be_clickable((By.XPATH, xpath))).click()

Alternatively, you can use the css selector in a similar way, but this time we are looking for a button with attribute shape=pill which is a child of a div with attribute role=button

css = "div[role='button'] button[shape='pill']"
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css))).click()

Notice that you can use .click() directly after the wait command command

Answered By: sound wave
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.