簡體   English   中英

使用 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(&quot;https://cdn.recreation.gov/public/images/76799.jpg&quot;);"></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.

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