策略/cookie的硒问题

2024-09-30 12:28:41 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:我无法单击“zgadzam sie”出现错误“selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法定位元素:{”方法“:“xpath”,“选择器”:”//span[@class='RveJvd snByac'和text()='Zgadzam się']”

问题:我如何处理? imageenglish image

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)

Tags: textimageimport元素timedriverseleniumxpath
2条回答

尝试单击按钮后,您正在睡觉。你也会在睡觉前离开司机,这是另一个问题

考虑使用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()


出现此错误的原因是element is nested in an ^{}。这可以通过等待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()

尝试使用完整的xpath。您可以使用通常作为浏览器扩展下载的xpath工具找到它

相关问题 更多 >

    热门问题