[英]Unable to find the value(element) in Xpath
即使網頁中存在該元素,也無法在 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 loop 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])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.