简体   繁体   中英

How do I make my code skip a line if a certain driver.find_element_by_xpath isnt found

starts here

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

#drivers
driver = webdriver.Chrome()
driver.get('https://www.target.com/p/plusone-waterproof-rechargeable-dual-vibrating-massager/-/A-76150669#lnk=sametab')

so if if ship isnt found i want addtoCart to work instead, and vise versa,

ship = driver.find_element_by_xpath('//*[@id="viewport"]/div[4]/div/div[2]/div[3]/div[1]/div/div[3]/div[1]/div[2]/button')
ship.click()

addtoCart = driver.find_element_by_xpath('//*[@id="addToCartButtonOrTextIdFor76150669"]')
addtoCart.click()

time.sleep(2)
cart = driver.get('https://www.target.com/cart')

currently trying to learn automation, want to make my own bot :) first time posting on here

Does the below accomplish what you need?

from selenium.common.exceptions import NoSuchElementException

try:
    ship = driver.find_element_by_xpath('//*[@id="viewport"]/div[4]/div/div[2]/div[3]/div[1]/div/div[3]/div[1]/div[2]/button')
    ship.click()
except NoSuchElementException:
    try:
        addtoCart = driver.find_element_by_xpath('//*[@id="addToCartButtonOrTextIdFor76150669"]')
        addtoCart.click()
    except NoSuchElementException:
        print("Can't click 'Ship' or 'Add to cart'")

time.sleep(2)
cart = driver.get('https://www.target.com/cart')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM