我正在尝试检查网站上是否存在两个元素(A,B)。我需要的是单击元素A(如果存在)(如果不存在的话),然后查找B并单击它(如果存在) 。以下是我的示例代码的一部分。
try:
abc= WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#rso > div > div > div:nth-child(1) > div > div > h3 > a")))
except NoSuchElementException:
continue
except TimeoutException:
continue
else:
element.click()
try:
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#rso > div > div > div:nth-child(1) > div > div > h3 > a")))
except NoSuchElementException:
continue
except TimeoutException:
continue
else:
abc.click()
time.sleep(randint(1, 15))
print('Process completed successfully')
我面临的问题是代码仅查找第一个元素,而不会继续进行下一个尝试。任何建议都很好。
答案 0 :(得分:1)
请尝试以下操作以单击第一个元素,如果找不到该元素,请单击第二个:
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "first.element"))).click()
except TimeoutException:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "second.element"))).click()
P.S。将"first.element"
,"second.element"
替换为真正的CSS选择器
如果页面上可能没有两个元素:
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "first.element"))).click()
except TimeoutException:
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "second.element"))).click()
except TimeoutException:
print("Both elements not found")