首页 > 解决方案 > 硒 - 政策/cookies的问题

问题描述

问题:我无法点击“zgadzam sie”。发生错误“selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“xpath”,“selector”:“//span [@class ='RveJvd snByac'和text( )='Zgadzam się']"}"

问题:我该如何处理? 图片 英文 图片

from selenium import webdriver
import time

driver= webdriver.Chrome()
driver.implicitly_wait(3)
driver.get("https://www.google.com/")
driver.find_element_by_xpath("//span[@class='RveJvd snByac' and text()='Zgadzam się']").click()
driver.quit()

time.sleep(5)

标签: pythonselenium

解决方案


尝试单击按钮后,您正在睡觉。您还在睡觉前退出驱动程序,这是另一个问题。

考虑使用WebDriverWait().until()函数来确保加载元素而不是依赖于任意时间量:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, "//span[@class='RveJvd snByac' and text()='Zgadzam się']"))
)

driver.find_element_by_xpath("//span[@class='RveJvd snByac' and text()='Zgadzam się']").click()


您收到此错误的原因是该元素嵌套在<iframe>. 这可以通过等待 iframe 出现,然后等待加载按钮,最后点击按钮来解决:

# Wait for the iFrame to be available to switch to it
WebDriverWait(driver, 10).until(
    EC.frame_to_be_available_and_switch_to_it(0)
)

# Wait for the button to be available within that iframe
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, "//span[@class='RveJvd snByac' and text()='Zgadzam się']"))
)

# Finally click the button
driver.find_element_by_xpath("//span[@class='RveJvd snByac' and text()='Zgadzam się']").click()

推荐阅读