【问题标题】:Can't seem to select Date range picker by it's XPATH using selenium似乎无法通过 XPATH 使用 selenium 选择日期范围选择器
【发布时间】:2021-03-20 07:14:35
【问题描述】:

我正在尝试从http://covid.gov.pk/stats/pakistan抓取数据。我希望脚本能够单击日期范围选择器来更改日期,但我似乎无法选择它我使用的 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[66]

我正在使用的 Python 脚本

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

driver = webdriver.Chrome()
driver.implicitly_wait(30)
driver.get("http://covid.gov.pk/stats/pakistan")

#wait for Page to load
WebDriverWait(driver, 30, ).until(EC.invisibility_of_element((By.XPATH, "//div[@id=\"preloader\"]")))

#select date range picker
element = 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[66]")
element.click()

我遇到的错误如下

无法定位元素:{"method":"xpath","selector":"//*[@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[66]"} (会话信息:chrome=81.0.4044.113)

我似乎无法弄清楚到底是什么不工作我通过使用 chrome 中的开发人员工具检查元素来复制 xpath。

【问题讨论】:

    标签: python html selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    日期选择器元素存在于iframe 中。您需要先切换iframe 才能访问日期选择器。

    诱导WebDriverWait() 并等待frame_to_be_available_and_switch_to_it() 并使用以下css选择器。

    然后您可以使用以下 xpath 点击日期选择器。

    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
    
    driver = webdriver.Chrome()
    driver.get("http://covid.gov.pk/stats/pakistan")
    #wait for Page to load
    WebDriverWait(driver,30).until(EC.invisibility_of_element((By.XPATH, "//div[@id='preloader']")))
    WebDriverWait(driver,20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,".pak-stats-ifrm")))
    #select date range picker
    element = driver.find_element_by_xpath("//div[@class='content-holder ng-scope']")
    element.click()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多