簡體   English   中英

嘗試使用 Selenium 查找按鈕

[英]Trying to Find a Button Using Selenium

紅色是我要訪問的按鈕

所以我試圖讓我的代碼點擊上圖中的紅色按鈕,但無論我嘗試什么 selenium 都會返回 NoSuchElementException。 你會怎么做 go? 因為我想不通。

如果您有興趣,這是我的代碼:

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

# Set up driver and remove weird error message that doesn't matter
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options)

# Get the webpage to interact with
driver.get('https://maps.google.com')

# Find search box and type into it
to_des = driver.find_element(By.ID, "searchboxinput").send_keys('McHenry Library')
enter = driver.find_element(By.ID, "searchboxinput").send_keys(Keys.ENTER)
# Line below should be clicking the button
directions = driver.find_element(By.XPATH, '//*[@id="QA0Szd"]/div/div/div[1]/div[2]/div/div[1]/div/div/div[4]/div[1]/button').click()
walking = driver.find_element(By.XPATH, '//*[@id="omnibox-directions"]/div/div[2]/div/div/div/div[4]/button').click()
from_des = driver.find_element(By.CLASS_NAME, 'tactile-searchbox-input')[2].send_keys('Oakes College')

您可以使用 xpath 單擊Direction文本:

//div[text()='Directions']

如果您想單擊方向圖標,您可以嘗試以下 Xpath:

//img[@alt='Directions']

如果這些都不起作用,請在單擊“方向”之前添加步驟以檢查窗格是否打開。 窗格可能需要一些時間才能打開,因此未找到該元素。

您在這里缺少的是:

  1. 創建良好的定位器
  2. 在准備好訪問元素時添加等待訪問元素。
    為此,我們通常使用WebDriverWait預期條件顯式等待。
    以下代碼有效:
from selenium import webdriver
from selenium.webdriver import Keys
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)
url = 'https://maps.google.com'
driver.get(url)
wait = WebDriverWait(driver, 20)

wait.until(EC.element_to_be_clickable((By.ID, "searchboxinput"))).send_keys('McHenry Library', Keys.ENTER)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[jsaction*='directions']"))).click()

我在這里使用 CSS 選擇器來定位directions按鈕,但這也可以使用 XPath 來完成。
因此,如果您更喜歡使用 XPath,可以使用它來代替我使用 CSS 選擇器的最后一行:

wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@jsaction,'directions')]"))).click()

暫無
暫無

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

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