首页 > 解决方案 > 无法使用 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)

网页代码图片如下:

在此处输入图像描述

谢谢你的帮助!

标签: pythonseleniumselenium-webdriverweb-scrapingselenium-chromedriver

解决方案


在 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突出显示


推荐阅读