Selenium Python定位AngularJS开发元素失败,求可行定位方案
Hey there! I see exactly where you're hitting a wall with this Selenium locator—let's fix it up together. The issue with your original approach is that Selenium's find_element_by_class_name() method only accepts a single class name, not multiple classes separated by spaces. When you pass "workstation-opconsultant-icon workstation-icon", it's looking for an element with that entire string as a single class (which doesn't exist here).
Here are several reliable, tested ways to locate this element successfully:
1. CSS Selector (Best for Multi-Class Elements)
Since your target element has two classes, use a CSS selector that targets both (note the no space between the class names—this tells Selenium to find an element that has both classes applied):
from selenium.webdriver.common.by import By # Directly target the element with both classes driver.find_element(By.CSS_SELECTOR, ".workstation-opconsultant-icon.workstation-icon")
To make this even more precise (and avoid accidental matches elsewhere on the page), you can combine it with the parent container's class:
# Narrow down using the parent homepage-tile class driver.find_element(By.CSS_SELECTOR, ".homepage-tile .workstation-opconsultant-icon")
2. XPath Locator (Flexible for DOM Traversal)
XPath is great if you need to tie the element to nearby content or use more complex matching:
- Match the exact class attribute string:
driver.find_element(By.XPATH, "//div[@class='workstation-opconsultant-icon workstation-icon']")
- Traverse from the adjacent "OP Clinic" text (super reliable if this text is static):
# Find the span with "OP Clinic" text, then grab its preceding div (the icon) driver.find_element(By.XPATH, "//span[text()='OP Clinic']/preceding-sibling::div")
A Quick Note on Angular's Generated Attributes
You’ll notice the _ngcontent-tby-c4 attribute in the HTML snippet—this is auto-generated by Angular and can change between builds or environments. It’s best to avoid using these for locators since they’re not stable long-term.
内容的提问来源于stack exchange,提问作者Pattabi

