即使网页中存在元素,也无法在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 ST 1循环45 ST 1 6 ST 1 89 ST 1
但运行以上代码时得到以下输出:23 ST 1循环4 ST 0 56 ST 0 7 ST 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
我也希望看到您的HTML或获取指向网页的链接以检查xpath。但是根据你的输出,我认为很可能你没有切换到[0]不存在的窗口。您正在if语句中执行窗口开关,因此如果这些条件都不满足,则不会切换窗口。尝试从窗口切换出你的if,也许是这样的:
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])
我认为你甚至不需要你的第二个if语句,因为它只包含
driver.close()
driver.switch_to.window(driver.window_handles[0])