繁体   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