我试图检查一个网站上是否存在两个元素(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')
我面临的问题是代码只查找第一个元素,并且不会继续进行下一次尝试。任何建议都会很棒。
尝试下面点击第一个元素,如果找不到 - 点击第二个:
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()
附:用真正的CSS选择器替换"first.element"
,"second.element"
如果页面上可能不存在这两个元素:
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")