为了账号安全,请及时绑定邮箱和手机立即绑定

无法使用 xpath 找到该元素,我确定它在驱动程序查找之前就存在

无法使用 xpath 找到该元素,我确定它在驱动程序查找之前就存在

FFIVE 2023-06-13 17:13:30
我正在尝试在无头模式下使用 selenium 从网站下载 excel 文件。虽然它在大多数情况下工作得很好,但在少数情况下(一年中的几个月) driver.find_element_by_xpath() 无法按预期工作。我浏览了很多帖子,虽然当驱动程序正在寻找它时该元素可能没有出现,但情况并非如此,因为我彻底检查了它并且还尝试使用 time.sleep() 来减慢进程,在附注我还使用 driver.implicitly_wait() 使事情变得更容易,因为网站实际上需要一段时间才能在页面上加载内容。我无法使用请求,因为它在获取请求的响应中不显示任何数据。我的脚本如下:from selenium import webdriverimport datetimefrom selenium.webdriver.chrome.options import Optionsfrom selenium.webdriver.support.ui import Selectimport osimport shutilimport timeimport calendarcurrentdir = os.path.dirname(__file__)Initial_path = 'whateveritis'chrome_options = Options()chrome_options.add_argument('--headless')chrome_options.add_argument('--no-sandbox')chrome_options.add_argument('--disable-dev-shm-usage')chrome_options.add_experimental_option("prefs", {                                                                                       "download.default_directory": f"{Initial_path}","download.prompt_for_download": False,"download.directory_upgrade": True,"safebrowsing.enabled": True})def save_hist_data(year, months):    def waitUntilDownloadCompleted(maxTime=1200):        driver.execute_script("window.open()")        # switch to new tab        driver.switch_to.window(driver.window_handles[-1])        # navigate to chrome downloads        driver.get('chrome://downloads')        # define the endTime        endTime = time.time() + maxTime        while True:            try:                # get the download percentage                downloadPercentage = driver.execute_script(                    "return document.querySelector('downloads-manager').shadowRoot.querySelector('#downloadsList downloads-item').shadowRoot.querySelector('#progress').value")                # check if downloadPercentage is 100 (otherwise the script will keep waiting)                if downloadPercentage == 100:                    # exit the method once it's completed                    return downloadPercentage            except:                pass
查看完整描述

1 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞

问题在于 except :异常处理。根据您的代码块,如果元素未找到"//td[@class='scwCells'  and contains(text(), '{no_of_days}')]"。由于 3 月 31 日的课程是scwCellsWeekend找不到元素。

  1. 按照第一个例外,它会处理一个IdentationException. 由于 element not found 不是 an IdentationException,因此除了异常处理外,它将用于下一个。

  2. 因为除了没有提到第二个条件外,NoSuchElementException 是在里面处理的。根据此处给出的代码,它正在尝试使用 xpath 搜索和元素//td[@class='scwInputDate' and contains(text(), '31')]。结果您再次找不到 NoSuchElementException。

您可以使用逻辑运算符或如下所示,而不是使用如此多的异常处理方案:

driver.find_element_by_xpath(f"//td[@class='scwCellsWeekend' and contains(text(), '{no_of_days}')] | //td[@class='scwCells' and contains(text(), '{no_of_days}')] | //td[@class='scwInputDate' and contains(text(), '{no_of_days}')]").click()



查看完整回答
反对 回复 2023-06-13
  • 1 回答
  • 0 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信