Home > Blockchain >  How do I use selenium in Python to select a calendar date when Python won't let me click on any
How do I use selenium in Python to select a calendar date when Python won't let me click on any

Time:01-09

I'm trying to click on the calendar in this website so I can choose a date to see the weather on that date:

Link

The first step would be to click on the calendar icon so the calendar shows up so I can click on a date. When I right-click on the icon and inspect it, this is the code:

<input name="ctl00$MainContentHolder$txtPastDate" type="date" value="2022-01-07" id="ctl00_MainContentHolder_txtPastDate" >

I try to do it in Python:

from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup as bs
from pandas.io.html import read_html
driver=wd.Chrome()
driver.maximize_window()
driver.get('https://www.worldweatheronline.com/kaohsiung-weather-history/tai-wan/tw.aspx')
f=get_html(driver)
driver.implicitly_wait(10)
driver.find_elements_by_id('ctl00_MainContentHolder_txtPastDate').click()

All I get is:

Traceback (most recent call last):

  File "<ipython-input-113-f6eee7773e00>", line 5, in <module>
    driver.find_elements_by_id('ctl00_MainContentHolder_txtPastDate').click()

AttributeError: 'list' object has no attribute 'click'

I can't seem to click anything because whenever I extract something, Python saves that thing as a list, and lists don't click.

I'm using Python 3.7.4 and Spyder 4.0.1

CodePudding user response:

Note that find_elements return a list of web element, not a single web element.

Also, on a python list we can not invoke .click method. that explain the error that you've got.

So instead of

driver.find_elements_by_id('ctl00_MainContentHolder_txtPastDate').click()

use this:

driver.find_element_by_id('ctl00_MainContentHolder_txtPastDate').click()

CodePudding user response:

Well, you can send keys too if you'd like to, with a desired date. Not every website facilitates with this feature (and this website has), but when it is there, you may use it. You may use the below locator strategy.

driver.find_element(By.CSS_SELECTOR, "input[type='date']").send_keys("05-01-2022")

Of course, do not hard-code the date into the code. Keep it in a variable.

  •  Tags:  
  • Related