使用Selenium提取多个href失败:仅能获取第一个链接的问题求助
Fix: Retrieving All href Links Instead of Just the First One
Hey Lara, I see the issue with your current code—let's get those two href links extracted properly!
What's Wrong with the Original Code
Your code has two key problems:
- You're using
find_element_by_css_selector()which only returns the first matching element in the DOM. To get all matches, you need the plural versionfind_elements_by_css_selector(). - Your CSS selector is targeting the wrong element: the
hrefattribute lives on the<a>tag inside.buySearchResultContentImg, not on a div. Also, class selectors in CSS need to start with a dot (.).
Correct Code to Extract Both Links
Here's how you can grab both href values:
# Get all the <a> elements inside .buySearchResultContentImg containers link_elements = driver.find_elements_by_css_selector(".buySearchResultContentImg > a") # Extract the href attribute from each element all_hrefs = [element.get_attribute("href") for element in link_elements] # Now all_hrefs will contain both links: ["carinfo-333285.php", "carinfo-333286.php"] print(all_hrefs)
Breakdown of the Fix
.buySearchResultContentImg > a: This selector targets every direct child<a>tag inside elements with the classbuySearchResultContentImg—exactly where your links are.find_elements_by_css_selector(): Returns a list of all matching elements, not just the first one.- List comprehension: Iterates over each element in the list and pulls out the
hrefattribute, giving you a clean list of all links.
If you're using a newer version of Selenium (4.0+), note that find_element_by_css_selector is deprecated—you should use find_element() with By.CSS_SELECTOR instead. Here's the updated syntax for newer versions:
from selenium.webdriver.common.by import By link_elements = driver.find_elements(By.CSS_SELECTOR, ".buySearchResultContentImg > a") all_hrefs = [element.get_attribute("href") for element in link_elements]
内容的提问来源于stack exchange,提问作者Lara19
相关产品推荐
相关产品推荐

