我想迭代某些元素,然后单击它们。在这个过程中,有人建议我使用Selenium的WebDriverWait,但是我遇到了一些困难,经过一段时间的尝试,还没有解决。
我的代码:
# finds all heart elements
hearts = driver.find_elements_by_xpath("//span[@class='fr66n']")
for h in range(len(hearts)):
try:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, hearts[h])));
ActionChains(driver).move_to_element(hearts[h]).click(hearts[h]).perform()
counter += 1
print(str(counter) + "/" + str(len(hearts)))
except exceptions.StaleElementReferenceException as e:
raise e
遇到错误:
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: 'value' must be a string
它指向这一行:
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, hearts[h])));
根据猜测,我认为它指的是hearts[h]应该是一个字符串,但不是已经这样了吗?希望我的解释是错误的,有人有更好的想法。谢谢。
最佳答案
hearts[h]
是 <element>
但你将它用作 Xpath 定位器 (By.XPATH, hearts[h])
使用索引选择元素,您可以这样做
xpathIndex = "(//span[@class='fr66n'])[{}]".format(h+1) # xpath index start from 1 not 0
# (//span[@class='fr66n'])[1]
element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, XpathIndex)));
ActionChains(driver).move_to_element(hearts[h]).click(hearts[h]).perform()
# or
# ActionChains(driver).move_to_element(element).click(element).perform()
关于python - 使用 Python 实现 WebDriverWait 时出现问题 - InvalidArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000797/