Home > database >  How to Use Selenium to Click Button/Link on Website in Python
How to Use Selenium to Click Button/Link on Website in Python

Time:03-01

I'm new to Selenium and I'm interested in using its power to open up a bunch of text files for daily reports from the enter image description here

CodePudding user response:

Try using this CSS Selector:

"#2020s > a"

Or Xpath

"//*[@id='2020s']/a"

Also try to add some wait after driver.get()

https://selenium-python.readthedocs.io/waits.html

CodePudding user response:

driver.get() does not wait for AJAX requests to complete before returning. The element you are trying to click is created via an AJAX request and does not yet exist at the time you are trying to click it.

To get around this, you must first wait for the element to be created, as in the following code.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Firefox(executable_path='xxx/geckodriver.exe'))
driver.get('https://mymarketnews.ams.usda.gov/viewReport/2837')
WebDriverWait(driver, timeout=10).until(EC.presence_of_element_located((By.ID, '2020s')))
elt = driver.find_element(By.XPATH, '//*[@id="2020s"]/a')
elt.click()

Two other things to note as you continue to work on this project are

  • CSS selectors have a limitation where they cannot be used to find an element with an ID starting with a number.
  • You need to click the <a> element directly, not the <li> element surrounding it.
  • Related