如何使用Selenium点击Administration横幅?已尝试find_element_by_class_name无效
Got it, let's break down why your find_element_by_class_name() attempt isn't working first: that method only accepts a single class name, but your target element has multiple classes (like wah-global-ask-banner-item-container5, wah-clickable, etc.). Passing multiple classes to it will throw an error or fail to find the element.
Here are a few reliable ways to locate and click this banner:
Option 1: Use the Element's ID (Most Reliable)
Your element has a unique id="admin-banner"—this is the best target since IDs are meant to be unique on a page:
# Using ID locator admin_banner = driver.find_element(By.ID, "admin-banner") admin_banner.click()
Option 2: Use CSS Selector with Specific Attributes
If the ID ever changes, you can use other unique attributes like data-provider="admin-link" or combine classes (note: in CSS selectors, you chain classes without spaces):
# Using data-provider attribute admin_banner = driver.find_element(By.CSS_SELECTOR, '[data-provider="admin-link"]') admin_banner.click() # Or using a combination of classes (pick a unique pair) admin_banner = driver.find_element(By.CSS_SELECTOR, '.wah-clickable.wah-provider-launch') admin_banner.click()
Option 3: Use XPath to Target the Title Text
You can also locate it by the "Administration" text inside the child element:
# XPath targeting the parent banner via the title text admin_banner = driver.find_element(By.XPATH, '//div[contains(text(), "Administration")]/..') admin_banner.click() # Or more precise XPath targeting the parent container directly admin_banner = driver.find_element(By.XPATH, '//div[@id="admin-banner"]') admin_banner.click()
Important: Wait for the Element to Be Interactable
If you're still having issues, it might be that the element isn't fully loaded yet when your code runs. Use explicit waits to ensure it's clickable first:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Wait up to 10 seconds for the element to be clickable admin_banner = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "admin-banner")) ) admin_banner.click()
Any of these methods should work way better than trying to use find_element_by_class_name() with multiple classes. Start with the ID method since it's the most straightforward and least likely to break if the page's classes get updated.
内容的提问来源于stack exchange,提问作者Luiz

