无法使用selenium按名称查找元素

iyfjxgzm  于 2022-12-26  发布在  其他
关注(0)|答案(1)|浏览(156)

我使用的是selenium 4.7.2,但无法通过元素名找到该元素。下面的代码返回NoSuchElementException错误:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Get the website using the Chrome webbdriver
browser = webdriver.Chrome()
browser.get('https://www.woofshack.com/en/cloud-chaser-waterproof-softshell-dog-jacket-ruffwear-rw-5102.html')

# Print out the result
price = browser.find_element(By.NAME, 'data-price-665')
print("Price: " + price.text)

# Close the browser
time.sleep(3)
browser.close()

使用find_element方法有什么问题?

8mmmxcuj

8mmmxcuj1#

看起来您在此处使用了错误的定位器。我在该页面上没有看到具有name属性值'data-price-665'的元素。
下面的代码是有效的:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)

wait = WebDriverWait(driver, 20)
actions = ActionChains(driver)

url = "https://www.woofshack.com/en/cloud-chaser-waterproof-softshell-dog-jacket-ruffwear-rw-5102.html"
driver.get(url)

price = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#product-price-665 .price")))
print("Price: " + price.text)

输出为:

Price: €112.95

相关问题