I want to select a button out of several buttons with the same class name from a website to click it. Something like this
<div class="reports">
<h1>First Reports</h1>
<p>Report 1</p>
<button class="report-button">Download</button>
<p>Report 2</p>
<button class="report-button">Download</button>
</div>
<div class="reports">
<h1>Second Reports</h1>
<p>Report 1</p>
<button class="report-button">Download</button>
<p>Report 2</p>
<button class="report-button">Download</button>
...
</div>
and I’d want to download Report 2 from second reports. One idea I had for this is to make an array of all elements with the report-button class and download the right one. The thing is the website might update and add more reports and mess up the ordering. Is there a better way to select Report 2?
I want to somehow navigate to Second Reports, then to Report 2, and then select the report-button class right after this paragraph element, but not sure how to do that in Selenium, or if it’s even possible.
>Solution :
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("your_website_url")
# Locate the second set of reports
second_reports = driver.find_elements(By.CSS_SELECTOR, '.reports')[1]
# Find Report 2 within the second set of reports
report2 = second_reports.find_element(By.XPATH, './/p[text()="Report 2"]')
# Find the adjacent report button element
report2_button = report2.find_element(By.XPATH, 'following-sibling::button[@class="report-button"]')
# Perform desired actions on the report button, such as downloading
report2_button.click()