python - 无法在 Xpath 中找到值(元素)

标签 python python-3.x selenium selenium-webdriver

即使网页中存在该元素,也无法在 xpath 中找到该元素。实际上代码既没有抛出异常,也没有找到元素。

for c in range(sheet.ncols):
    for r in range(sheet.nrows):
        st = (sheet.cell_value(r, c))
        print(str(st))
        xpath1 = "//input[@value='Analyze' and contains(@onclick,'" + str(st) + "')]"
        #xpath = "//input[@value='Analyze'][.='" + st + "']"
        print(driver.title)
        print(len(driver.find_elements_by_xpath(xpath1)))
        if driver.find_elements_by_xpath(xpath1):
            print("loop")
            driver.find_element_by_xpath(xpath1).click()  # Here new window will open
            time.sleep(2)
            #Main_Window = driver.current_window_handle
            driver.switch_to.window(driver.window_handles[-1])
            driver.find_element_by_xpath('/html/body/table/tbody/tr[4]/td/table/tbody/tr[9]/td[3]/input').click()
            driver.close()
            driver.switch_to.window(driver.window_handles[-1])
            xpath2 = "//*[@id='create_button']"
            xpath3 = "//*[@id='update_button']"
            if check_exists_by_xpath(xpath2):
                driver.find_element_by_xpath(xpath2).click()
                driver.close()
                driver.switch_to.window(driver.window_handles[0])

            elif check_exists_by_xpath(xpath3):
                driver.close()
                driver.switch_to.window(driver.window_handles[0])
                continue

预期输出应该是:

23 英石 1 环形 45 英石 1 6 英石 1 89 英石 1

但是运行上面的代码时得到以下输出: 23 英石 1 环形 4 英石 0 56 英石 0 7 英石 0

代码有什么问题?

提前致谢。

最佳答案

只需切换到正确的窗口和框架即可。

      if check_exists_by_xpath(xpath2):
            driver.find_element_by_xpath(xpath2).click()

      #else not required as you are not using the xpath3 to click

      driver.close()
      driver.switch_to.window(driver.window_handles[0])
      driver.switch_to.frame(base_frame_locator/index)
      driver.switch_to.frame(child_frame_locator/index)
      continue

关于python - 无法在 Xpath 中找到值(元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55213874/

相关文章:

Python3,数组中的列名 - numpy 或 pandas

python - 如何通过 Python 使用 Selenium 在 invisibility_of_element_located 上等待多个条件

javascript - 如何将键发送到焦点元素?

python - 使用 fastcgi 在 lighttpd 中托管 Flask 应用程序

Python pretty-print 嵌套对象

python - django 将额外的参数传递给filterset_class

Python 脚本不遍历数组

Python-OpenCV 查找矩形并裁剪图像

java - 无法使用 selenium 传递客户 ID 中的任何值

python - cx_Freeze - opencv 兼容性