如何使用Selenium和Python单击日历上的特定日期

2024-04-24 19:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个包含多个下拉菜单和表格的网站中使用Selenium读取数据。 这是链接:“https://markets.ft.com/data/funds/tearsheet/historical?s=NL0006294175:EUR”。在

我需要改变日期范围,假设我想看到1月1日到1月5日这只股票的价格,所以我点击两个小日历。从左边的表中选择并单击某个日期是可以的,我使用xpath和css选择器成功地做到了。在

不过,点击右边表格中的日期真的很难,我不明白为什么。 Python总是显示以下错误:

selenium.common.exceptions.ElementNotVisibleException: Message: element not interactable

我的代码是:

^{pr2}$

我也尝试过使用ActionChains和WebDriverWait,但都没用。 我怀疑问题是这两个表非常相似,selenium试图访问第一个表,即使它不再可见,但我真的不知道如何修复它。在

你知道有没有办法点击第二个表中的日期?在

提前谢谢。在


Tags: httpscomdata网站链接selenium读取数据表格
3条回答

问题是有两个元素与您在该页上提到的选择器匹配。最简单的检查方法是打开浏览器控制台,手动查看案例。在

你需要一种方法来区分这两者。为了获得清晰的xpath,一次只能打开一个日期选择器。然后你可以用下面的方法来匹配。在

//div[contains(@class,'picker--opened')]//*[@aria-label='5 Jan, 2019']

您可以尝试下面的代码为日历事件。在

driver.findElement(By.xpath("//div[contains(@class, 'date--from')]")).click();
driver.findElement(By.xpath("//div[contains(@class, 'date--from')]//div[contains(@class,'picker__nav--next')]")).click();
driver.findElement(By.xpath("//div[contains(@class, 'date--from')]//div[@aria-label='1 Jan, 2019']")).click();
driver.findElement(By.xpath("//div[contains(@class, 'date--to')]")).click();
driver.findElement(By.xpath("//div[contains(@class, 'date--to')]//div[contains(@class,'picker__nav--next')]")).click();
driver.findElement(By.xpath("//div[contains(@class, 'date--to')]//div[@aria-label='5 Jan, 2019']")).click();

如果它不工作,你可以使用一些等待后日历点击让日历打开。在

有2个问题,当你点击第一个日期时会有重叠的元素阻止点击第二个输入,你需要等到这个元素被删除,你需要选择第二个输入日期就可以用xpath(//the_xpath_selector)[2]

driver.get(r'https://markets......')
driver.find_element_by_css_selector('h2 span[data-mod-action="toggle-filter"]').click()
# 4 input, index 1 and 3 are hidden
inputDate = driver.find_elements_by_css_selector('.mod-ui-date-picker input')
inputDate[0].click()
driver.find_element_by_xpath('//*[@title="Next month"]').click()
driver.find_element_by_xpath("//*[@aria-label='1 Jan, %d']" %(y)).click() 
# wait until the element removed
wait.until(
    lambda d: len(d.find_elements_by_css_selector('.mod-ui-loading__overlay')) == 0
)
inputDate[2].click()
# select second date piker "[2]"
driver.find_element_by_xpath("(//*[@aria-label='5 Jan, %d'])[2]" %(y)).click()

相关问题 更多 >