python - 无法使用 selenium 在 Web 上找到该元素
问题描述
我需要你的帮助,拜托。我正在使用 selenium 单击网页上的按钮,然后打开其他选项。不幸的是,它无法识别 Path 元素。网络模拟器是移动版,因为它更容易访问按钮(问题与桌面版相同)。我试图点击网页上的其他按钮,它工作正常。
mobile_emulation = { "deviceName": "Galaxy S5" }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(chromedriver_path, options=chrome_options)
driver.get('https://www...')
time.sleep(20)
Click1 = driver.find_element_by_xpath('//*[@id="header_3"]/div')
Click1.click()
错误是:
NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="header_3"]/div"}
(Session info: chrome=93.0.4577.82)
网页代码图片如下:
谢谢你的帮助!
解决方案
在 Selenium 中有 4 种点击方式。
我将使用这个 xpath
//div[contains(@id, 'header_3')]//div
代码试用1:
time.sleep(5)
driver.find_element_by_xpath("//div[contains(@id, 'header_3')]//div").click()
代码试用2:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@id, 'header_3')]//div"))).click()
代码试用3:
time.sleep(5)
button = driver.find_element_by_xpath("//div[contains(@id, 'header_3')]//div")
driver.execute_script("arguments[0].click();", button)
代码试用4:
time.sleep(5)
button = driver.find_element_by_xpath("//div[contains(@id, 'header_3')]//div")
ActionChains(driver).move_to_element(button).click().perform()
进口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
PS:如果我们有唯一的条目,请检查dev tools
(谷歌浏览器)。HTML DOM
检查步骤:
Press F12 in Chrome
-> 转到element
部分 -> 做一个CTRL + F
-> 然后粘贴xpath
并查看,如果您想要element
突出显示。
推荐阅读
- asp.net-core-mvc - 在 ASP.NET Core 3.0 API 中,如何实现 JWT Bearer Tokens
- java - 当我在 Activity 中调用构造函数时应用程序崩溃
- excel - CountIf 在两个文件上
- python - 如何解决 DJANGO_SETTINGS_MODULE 的问题?
- php - 如果页面网址与我提供的完全相同,则适用条件
- python - Kivy TypeError 不支持的操作数类型
- excel - 求每“X”行的平均值
- c++ - operator<< 如何与操纵器函数一起使用
- c# - 如何在 ASP.NET Core Web API 中管理 EFCore DbContext 生命周期?
- objective-c - 您可以在 Objective-C 中创建仅在您的库中可见的类方法吗?