You need to enable JavaScript to run this app. Python Selenium抓取谷歌搜索结果链接失效 求替代XPath方案
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium抓取谷歌搜索结果链接失效 求替代XPath方案

你遇到的问题是谷歌搜索结果页的前端结构已更新,原先用于包裹标题的r类名已被废弃,所以原有XPath无法匹配到目标元素。

可用的替代XPath

1. 通用搜索结果链接定位(和原逻辑一致,提取所有搜索结果的跳转链接)

使用以下代码替换原有定位语句即可:

profiles = driver.find_elements_by_xpath('//div[@id="search"]//div[contains(@class, "g")]//a[@href]')

注:当前谷歌搜索结果的每个独立结果块都保留g类名,该定位方式可以准确匹配每个结果块内的首个跳转链接

2. 适配领英主页提取的精准定位

你当前的需求是提取领英个人主页链接,可以直接通过href特征匹配,稳定性更高,即使谷歌外层结构调整也不会失效:

profiles = driver.find_elements_by_xpath('//div[@id="search"]//a[contains(@href, "linkedin.com/in/")]')

额外优化建议

  • 替换固定time.sleep()为显式等待,避免网络波动导致的元素未加载就执行定位的问题,示例代码如下:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 最多等待10秒,直到目标元素全部加载完成
wait = WebDriverWait(driver, 10)
profiles = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@id="search"]//a[contains(@href, "linkedin.com/in/")]')))
  • 谷歌搜索的num参数最大生效值为100,你设置的num=200实际只会返回100条结果,需要更多结果需要自行处理翻页逻辑。
  • 如果你使用的是Selenium 4.0+版本,原有的find_elements_by_xpath方法已被废弃,建议统一使用以下写法:
profiles = driver.find_elements(By.XPATH, '//div[@id="search"]//a[contains(@href, "linkedin.com/in/")]')

内容的提问来源于stack exchange,提问作者abbasgol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 03:06:04