You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium提取多个href失败:仅能获取第一个链接的问题求助

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:

  1. 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 version find_elements_by_css_selector().
  2. Your CSS selector is targeting the wrong element: the href attribute lives on the <a> tag inside .buySearchResultContentImg, not on a div. Also, class selectors in CSS need to start with a dot (.).

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 class buySearchResultContentImg—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 href attribute, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:52:29