【问题标题】:Not being able to find an element by xpath using python selenium无法使用 python selenium 通过 xpath 找到元素
【发布时间】:2020-04-24 08:15:05
【问题描述】:

我想使用 selenium 单击一个按钮,然后在网站的下拉日期选择器上选择该按钮。

The button I wish to click is highlighted in yellow

http://covid.gov.pk/stats/ict

我正在使用以下 xpath。

//*[@id="datepicker-1361-7562-title"]/strong

这是我正在使用的代码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from datetime import date
import time

#calculating days from first day 
d1 = date(2020, 3, 10)
dCurrent = date.today()
daysElapsed = int((dCurrent - d1).days)

#setting up driver and fetching website
driver = webdriver.Chrome()
driver.get('http://covid.gov.pk/stats/ict')

#wait for page and resources to load
WebDriverWait(driver, 25).until(EC.invisibility_of_element((By.XPATH, "//div[@id=\"preloader\"]")))
WebDriverWait(driver, 15).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//*[@id="app"]/div[2]/iframe')))


driver.find_element_by_xpath('//*[@id="body"]/div/div/div[1]/div[2]/div/div[1]/div[1]/div[1]/div/lego-report/lego-canvas-container/div/file-drop-zone/span/content-section/canvas-component[29]/div/div/div/div/ga-date-range-picker/lego-date-duration-control/control-layout-wrapper/button/div').click()
time.sleep(3)
driver.find_element_by_xpath('//*[@id="datepicker-1361-7562-title"]/strong').click()

问题是我可以点击下拉菜单上的其他元素,而不是这个按钮。

我在运行代码时遇到的错误。

在 check_response 中 raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such 元素:无法定位元素: {"method":"xpath","selector":"//*[@id="datepicker-1361-7562-title"]/strong"} (会话信息:chrome=81.0.4044.122)

我一直在尝试解决此问题,但似乎无法确定我到底做错了什么,我们将不胜感激。

【问题讨论】:

  • 好的,我已经意识到我的错误,经过进一步检查,我发现每次打开下拉菜单时。月/年按钮的 id 更改。我所要做的就是使用其他属性来选择元素。

标签: python selenium web-scraping


【解决方案1】:

切换到框架并点击日历后,第一部分'startDate'可以找到带有以下选择器的年份按钮

driver.find_element_by_xpath('//div[@ng-model='$ctrl.calendarDateRange.startDate']//table[@class='uib-daypicker']//button[contains(@id, 'datepicker-')]').click()

如果您希望点击“结束日期”部分更改//div[@ng-model=''] 的路径

【讨论】:

  • 谢谢。我应该为我的选择器尝试另一种方法。 xpath 使用 ID 来选择元素,而每次呈现日历时,它都会更改该 ID,因为我的代码无法正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-16
  • 1970-01-01
  • 2017-12-12
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多