簡體   English   中英

如果找不到某個 driver.find_element_by_xpath,如何讓我的代碼跳過一行

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

從這里開始

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')

所以如果沒有找到船,我想讓 addtoCart 工作,反之亦然,

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')

目前正在嘗試學習自動化,想制作我自己的機器人 :) 第一次在這里發帖

以下是否滿足您的需求?

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM