[英]Finding Add To Cart button with selenium using find_element_by_xpath
[英]Finding an element using find_element_by_xpath
我试图通过 xpath 找到一个元素,但它没有返回任何内容。 除了 xpath 之外,似乎所有 find_elements 方法都有效。 我正在尝试查找可点击的文本 Ponderosa Campground。
def searchCondition():
elem = driver.find_elements_by_xpath("//div[@aria-label='PONDEROSA CAMPGROUND']")
elem.click()
这是我试图找到元素的 URL 。 https://www.recreation.gov/search?q=Ponderosa%20Campground
<div data-component="FocusManager" tabindex="-1" style="outline: none;">
<div class="flex-grid search-outer-wrap" data-component="FlexRow">
<div class="flex-col-12" data-component="FlexCol">
<div class="rec-flex-card-wrap " id="rec-card-233118_campground">
<a data-card="true" class="rec-flex-card-image-wrap" href="/camping/campgrounds/233118" target="_blank" rel="noopener noreferrer" alt="PONDEROSA CAMPGROUND">
<div data-component="FauxImage" class="sarsa-faux-image rec-flex-card-image-wrap-faux-image" role="img" aria-label="PONDEROSA CAMPGROUND" style="min-height: 155px; background-image: url("https://cdn.recreation.gov/public/images/76799.jpg");"></div></a>
<div class="rec-flex-card-content-wrap"><a href="/camping/campgrounds/233118" target="_blank" rel="noopener noreferrer" aria-label="PONDEROSA CAMPGROUND - 2.6 stars / $25 / night">
这是完整的脚本。
import time
from time import sleep
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
import pause
import pyperclip
# Definitions
ID = ""
PW = ""
SRCH = "Ponderosa Campground"
URL = "https://www.recreation.gov/search?q=Ponderosa%20Campground"
now = datetime.now()
options = Options()
options.headless = False
# executable_path for webdriver
driver = webdriver.Chrome(
executable_path='C:/chromedriver.exe',
options=options)
wait = WebDriverWait(driver, 50)
driver.get(URL)
def searchClick():
CampBtn = wait.until(EC.element_to_be_clickable((By.XPATH,"//a[@alt='PONDEROSA CAMPGROUND']"))).click()
elem = driver.find_element_by_xpath("//a[@alt='PONDEROSA CAMPGROUND']")
if elem.isDisplayed():
print(elem)
elem.click()
else:
print("no availability")
searchCondition()
time.sleep(20)
您必须将 xpath 指向交互式元素,例如a
, input
, button
并且必须在预期条件下诱导一些显式等待,以检查该元素是否已全部设置为执行单击操作。 例如 -
WebDriverWait(web, 20).until(EC.element_to_be_clickable((By.XPATH,"//a[@alt='PONDEROSA CAMPGROUND']")))
elem = web.find_element_by_xpath("//a[@alt='PONDEROSA CAMPGROUND']")
elem.click()
单击图像后,它将打开新选项卡,如下所示。 要查看此操作,请在单击操作后添加一些等待时间 -
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.