How to click on the first link of an opensecrets page without getting an indexError?

Viewed 24

I'm trying to click on the first link in the results page of an opensecrets.org query. I've searched "chase" using selenium, and I now want to go to the page of the first link available. Eventually I want to loop through a whole list of searches and click on the first link, but now I can't even get my code to run with this one element's specific xpath. When I run this code:

result = driver.find_elements_by_xpath(
    '//*[@id="___gcse_0"]/div/div/div/div[5]/div[2]/div/div/div[1]/div[1]/div[1]/div[1]/div/a')[0]
result.click()

I get an error: IndexError: list index out of range. Does anyone know why I'm getting this error or is there a more general way to do this, so that I could do it with any search? I keep seeing answers to click on the first link of a google search, but they all use the tag_name "cite" so I'm unsure of how to apply this to an opensecrets search

1 Answers

to just click on the first link, you can use the below xpath :

(//a[contains(@class, 'gs-title')])[1]

and in code, you can use it like this :

wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "(//a[contains(@class, 'gs-title')])[1]"))).click()

Imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC4
from selenium.webdriver.common.action_chains import ActionChains

and if you'd like to do it from loop :

counter = 1
action = ActionChains(driver)
for link in driver.find_elements(By.XPATH, f"(//a[contains(@class, 'gs-title')])[{counter}]"):
    action.move_to_element(link).click().perform()
    if counter == 1:
        break
    counter = counter + 2
Related