Shrey
Shrey

Reputation: 156

Unable to locate element using selenium (Python)

I have been trying to find a button a click on it but no matter what I try it has been unable to locate it. I have tried using all the driver.find_element_by... methods but nothing seems to be working

from selenium import webdriver
import time


driver = webdriver.Chrome(executable_path="/Users/shreygupta/Documents/ComputerScience/PythonLanguage/Automation/corona/chromedriver")
driver.get("https://ourworldindata.org/coronavirus")
driver.maximize_window()
time.sleep(5)
driver.find_element_by_css_selector("a[data-track-note='chart-click-data']").click()

I am trying to click the DATA tab on the screenshot below enter image description here

Upvotes: 0

Views: 127

Answers (2)

Svetlana Levinsohn
Svetlana Levinsohn

Reputation: 1556

You can modify your script to open this graph directly:

driver.get("https://ourworldindata.org/grapher/total-cases-covid-19")
driver.maximize_window()

Then you can add implicitly_wait instead of sleep. An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or elements) not immediately available (from python documentation). It'll work way faster because it'll interact with an element as soon as it finds it.

driver.implicitly_wait(5)
driver.find_element_by_css_selector("a[data-track-note='chart-click-data']").click()

Hope this helps, good luck.

Upvotes: 1

supputuri
supputuri

Reputation: 14135

Here is the logic that you can use, where the script will wait for max 30 for the Data menu item and if the element is present with in 30 seconds it will click on the element.

url = "https://ourworldindata.org/grapher/covid-confirmed-cases-since-100th-case"
driver.get(url)
driver.maximize_window()
wait = WebDriverWait(driver,30)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"a[data-track-note='chart-click-data']"))).click()

Upvotes: 1

Related Questions