I am trying to use selenium to click into a link and then back out. I am new to programming , but I have watched a few tutorials about this and still cannot click into the page. My code is below any help would be appreciated! when I was just trying to pull the building names from the website that worked. I cannot seem to figure out why this does not.
## LEED v3 2009 texas
driver.get("https://www.usgbc.org/projects/?Country=%5B%22United+States%22%5D&Rating+System=%5B%22New+Construction%22%5D&Rating+Version=%5B%22v2009%22%5D&Certification=%5B%22Platinum%22%5D&State=%5B%22Texas%22%5D")
#check this is the right website
#print(driver.title)
buildings = []
try:
project_profiles = driver.find_elements(By.CLASS_NAME, "grid-item--title")
for profile in project_profiles:
building_name = profile.text
buildings.append(building_name)
print(building_name)
#load building profile page
building_profile_link = driver.find_element(By.LINK_TEXT, building_name).click()
time.sleep(5)
driver.back()
except:
driver.quit()
I tried using just the string and also the variable name but neither worked
There are two things that you have to fix First is Replace Find by Linktext with PARTIAL_LINK_TEXT
building_profile_link = driver.find_element(By.PARTIAL_LINK_TEXT, building_name)
Second is Once you click on the link in current page, go to next page and come back the project_profiles elements list will become stale and you will get stale element reference on clicking , so you should find the list again to avoid that
Complete code Fixed
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get(
"https://www.usgbc.org/projects/?Country=%5B%22United+States%22%5D&Rating+System=%5B%22New+Construction%22%5D&Rating+Version=%5B%22v2009%22%5D&Certification=%5B%22Platinum%22%5D&State=%5B%22Texas%22%5D")
# check this is the right website
# print(driver.title)
buildings = []
try:
project_profiles = driver.find_elements(By.CLASS_NAME, "grid-item--title")
for i in range(len(project_profiles)):
# Wait for page to load as order of elements will be incorrect otherwise
time.sleep(5)
project_profiles = driver.find_elements(By.CLASS_NAME, "grid-item--title") # Find the list again
building_name = project_profiles[i].text
buildings.append(building_name)
print(building_name)
# load building profile page
building_profile_link = driver.find_element(By.XPATH, f"//div[@id='result-grid']//h1[text()='{building_name}']")
building_profile_link.click()
time.sleep(5)
driver.back()
except Exception as e:
print(e)
driver.quit()