我正在使用 Selenium 与网站交互,但遇到了图标不可交互的问题。 这是我要单击的图标: 在此输入图片描述
使用 XPath //*[@id='unregUserDropdown'] 定位图标。
我已经确认找到了该元素,因为我可以打印其外部 HTML。但是,当我尝试使用 ActionChains 与其交互时,它没有响应。 这是代码:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
# Setup Chrome options
chrome_options = Options()
# chrome_options.add_argument("--headless") #options=chrome_options
# Setup Selenium webdriver
driver = webdriver.Chrome()
# Open the website
driver.get('https://www.investagrams.com/') # Replace with your URL
wait = WebDriverWait(driver, 10) # Wait up to 10 seconds
try:
# Now find the icon
icon = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='unregUserDropdown']")))
print("Icon found!")
print("Icon HTML: ", icon.get_attribute('outerHTML'))
# Interact with the icon
actions = ActionChains(driver)
actions.move_to_element(icon)
actions.click(icon)
actions.perform()
except TimeoutException:
print("Element not found.")
# Close the browser
driver.quit()
我还使用了单击方法并导致“消息:元素不可交互”。 这是代码:
try:
# Now find the icon
icon = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='unregUserDropdown']")))
print("Icon found!")
print("Icon HTML: ", icon.get_attribute('outerHTML'))
icon.click()
except TimeoutException:
print("Element not found.")
我尝试了多种方法来解决此问题,包括:
使用WebDriverWait和expected_conditions.visibility_of_element_ located等待元素可见。 检查元素是否位于 iframe 内,并在必要时切换到它。 执行 JavaScript 以单击该元素。 检查元素是否位于影子 DOM 内。 尽管进行了这些尝试,该图标仍然没有响应。我正在使用的网站是“https://www.investagrams.com/”。我使用 Chrome 作为浏览器,并使用 Selenium 的 Python 绑定来实现自动化。
我所需要做的就是单击该图标,以便出现一个下拉窗口,然后单击登录。 有人对为什么图标可能无法交互以及我如何与其交互有任何建议吗?
看来你应该首先登录该网站,然后运行该程序。 直到用户登录后,图标的 xpath 才会激活。