这是我的代码:
def CheckQueue(driver):
qdone = False
qID_xpath_start = "/html/body/div[5]/form/table/tbody[1]/tr["
qID_xpath_end = "]/td[2]/a"
qIDindex = 1
while qdone == False:
print "enter loop"
print driver.find_element_by_xpath(qID_xpath_start+str(qIDindex)+qID_xpath_end).text #This prints
try:
element = WebDriverWait(driver, 6000).until(ec.presence_of_element_located(By.XPATH((qID_xpath_start+str(qIDindex)+qID_xpath_end)))) #This fails
print "found"
except:
qdone= True
print "could not be found"
print driver.find_element_by_xpath(qID_xpath_start+str(qIDindex)+qID_xpath_end).text
if qdone == False:
print driver.find_element_by_xpath(qID_xpath_start+str(qIDindex)+qID_xpath_end).text
print "testing"
qIDindex +=1
print "loop"
return driver
我得到了这个(14453是我正在寻找的xpath的链接文本)
enter loop
14453
could not be found
14453
loop
看来我的代码能够找到链接,但当被要求检查链接是否存在时,它会失败,并激活except语句。如果已经找到并打印出来,它为什么会失败?
此外,即使我已经分配了很多时间,它几乎立即失败了。
知道我哪里错了吗?
我试过
element = WebDriverWait(driver, 6000).until(ec.presence_of_element_located(By.XPATH((qID_xpath_start+str(qIDindex)+qID_xpath_end))))
element = WebDriverWait(driver, 6000).until(EC.presence_of_element_located(By.XPATH((qID_xpath_start+str(qIDindex)+qID_xpath_end))))
element = WebDriverWait(driver, 6000).until(ec.presence_of_element_located(By.XPATH, qID_xpath_start+str(qIDindex)+qID_xpath_end))
element = WebDriverWait(driver, 6000).until(ec.presence_of_element_located(By.xpath, qID_xpath_start+str(qIDindex)+qID_xpath_end))
我使用的是Python 2.7,Selenium 2.43,Firefox 23.0.3
顺便说一下,为了测试是否可以在某些点找到xpath元素,我会抛出一些可能感觉不合适的打印语句。
编辑:当我删除我的try语句时,我收到此错误。
element = WebDriverWait(driver, 6000).until(EC.presence_of_element_located(By.XPATH((qID_xpath_start+str(qIDindex)+qID_xpath_end))))
NameError:未定义全局名称“By”
我的代码中有以下import语句:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.action_chains import ActionChains
我认为我确实需要添加一个import语句,但我似乎无法找到如何导入By。
我试过了:
from selenium.webdriver.common.by import By
当我运行它时,我已经超过了该错误但收到了此错误:
element = WebDriverWait(driver,6000).until(EC.presence_of_element_located(By.XPATH((qID_xpath_start + str(qIDindex)+ qID_xpath_end)))) TypeError:'str'对象不可调用
然后我更新了我的WebDriverWait行以反映alecxe的建议。
element = WebDriverWait(driver, 6000).until(EC.presence_of_element_located((By.XPATH, qID_xpath_start+str(qIDindex)+qID_xpath_end)))
现在它似乎正在发挥作用。
答案 0 :(得分:12)
WebDriverWait
expression syntax不正确,应该是:
WebDriverWait(driver, 60).until(ec.presence_of_element_located((By.XPATH, qID_xpath_start+str(qIDindex)+qID_xpath_end)))
请注意元组已传入presence_of_element_located()
方法。
请注意,此处60
为60 秒。
此外,为了成功调试和理解正在发生的事情,让它失败通常会有所帮助 - 删除try/except
并查看引发的错误类型。